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 的优化渲染)
相关推荐
running up10 小时前
Pinia 完整使用指南
vue
安_11 小时前
<style scoped>跟<style>有什么区别
前端·vue
辛-夷14 小时前
TS封装axios
前端·vue.js·typescript·vue·axios
@AfeiyuO1 天前
Vue3 矩形树图
vue·echarts
weixin_422555422 天前
ezuikit-js官网使用示例
前端·javascript·vue·ezuikit-js
zhz52142 天前
代码之恋(第十五篇:分布式心跳与网络延迟)
网络·分布式·ai·重构·vue·结对编程
元亓亓亓2 天前
考研408--计算机网络--day9--路由&RIP&OSPF
网络·计算机网络·路由·rip
我看刑2 天前
【已解决】el-table 前端分页多选、跨页全选等
前端·vue·element
sg_knight2 天前
拥抱未来:ECMAScript Modules (ESM) 深度解析
开发语言·前端·javascript·vue·ecmascript·web·esm
汝生淮南吾在北2 天前
SpringBoot3+Vue3小区物业报修系统+微信小程序
微信小程序·小程序·vue·毕业设计·springboot·课程设计·毕设