Vue3 中 createWebHistory 和 createWebHashHistory 的区别

发布于:2024-04-23 ⋅ 阅读:(23) ⋅ 点赞:(0)

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 的优化渲染)