拉不拉稀肚拉稀 发表于 2024-6-15 00:07:27

Vue3 中 createWebHistory 和 createWebHashHistory 的区别

createWebHistory



[*]创建方式: 使用 createWebHistory 函数来创建基于 HTML5 History API 的路由。
import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import About from '@/views/About.vue'

const router = createRouter({
history: createWebHistory(),
routes: [
    {
      path: '/home',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      component: About
    }
]
})


[*]使用方式: 在大多数当代欣赏器中,使用标准的 URL 格式,没有 # 符号。
[*]在欣赏器中的显示方式: 显示为通例的 URL,比方https://mp.csdn.net/mp_blog/manage/article。
缺点:
服务器配置: 必要服务器配置来处理所有路由请求,以便精确地返回 index.html 文件,以便在客户端渲染应用程序。
刷新时问题: 刷新页面时,如果服务器不精确配置,会导致 404 错误,因为服务器无法找到对应的路由。


[*]优化方式:
服务器配置: 必要在服务器上进行配置,以确保在路由请求时精确地返回 index.html 文件。比方,在使用 Nginx 时,可以使用 try_files 指令。
历史模式兼容性: 如果思量兼容性,可以使用 createWebHashHistory 替换,不必要特殊的服务器配置。
createWebHashHistory



[*]创建方式: 使用 createWebHashHistory 函数来创建基于 URL 哈希的路由。
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import About from '@/views/About.vue'

const router = createRouter({
history: createWebHashHistory(),
routes: [
    {
      path: '/home',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      component: About
    }
]
})


[*]使用方式: 在 URL 中使用 # 符号来表示路由。
[*]在欣赏器中的显示方式: URL 中会包含 # 符号,比方https://mp.csdn.net/mp_blog/manage/#/article。
缺点:
丑陋的 URL: URL 包含 # 符号,看起来较为丑陋。
SEO 问题: 对于搜索引擎优化不友好,因为搜索引擎不会剖析 # 符号后的内容。
[*]优化方式:
美化 URL: 可以通过其他技术手段(如路由别名)来美化 URL,淘汰 # 符号的影响。
服务端渲染: 如果思量 SEO,可以思量使用服务端渲染来解决 SEO 问题,但这会增长应用程序的复杂性。
(使用 Thymeleaf 模板引擎配合Spring Boot 的优化渲染)

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Vue3 中 createWebHistory 和 createWebHashHistory 的区别