Vue3 中 createWebHistory 和 createWebHashHistory 的区别

createWebHistory

  • 创建方式: 使用 createWebHistory 函数来创建基于 HTML5 History API 的路由。
javascript 复制代码
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 哈希的路由。
javascript 复制代码
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 的优化渲染)
相关推荐
Cult Of1 天前
Alicea Wind的个人网站开发日志(2)
开发语言·python·vue
Byron07072 天前
从多端割裂到体验统一:基于 Vue 生态的跨端架构落地实战
vue·多端
计算机程序设计小李同学2 天前
基于 Spring Boot + Vue 的龙虾专营店管理系统的设计与实现
java·spring boot·后端·spring·vue
沐墨染2 天前
Vue实战:自动化研判报告组件的设计与实现
前端·javascript·信息可视化·数据分析·自动化·vue
奔跑的呱呱牛2 天前
viewer-utils 图片预览工具库
javascript·vue·react
Cult Of2 天前
Alicea Wind的个人网站开发日志(1)
python·vue
Polaris_YJH2 天前
使用Vue3+Vite+Pinia+elementUI搭建初级企业级项目
前端·javascript·elementui·vue
Mr Xu_2 天前
【Vue3 + ECharts 实战】正确使用 showLoading、resize 与 dispose 避免内存泄漏
前端·信息可视化·vue·echarts
换日线°3 天前
前端炫酷展开效果
前端·javascript·vue
IT北辰3 天前
基于Vue3+python+mysql8.0的财务凭证录入系统,前后端分离完整版(可赠送源码)
python·vue