不同的历史模式
原创2026/3/5大约 2 分钟
在创建路由器实例时,history 配置允许我们在不同的历史模式中进行选择
Hash 模式
hash 模式是用 createWebHashHistory() 创建的
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: () => import('../views/home/home.vue'),
},
{
path: '/about',
name: 'about',
},
],
})
export default routerHTML5 模式
用 createWebHistory() 创建 HTML5 模式,推荐使用这个模式
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: () => import('../views/home/home.vue'),
},
{
path: '/about',
name: 'about',
},
],
})
export default router当使用这种历史模式时,URL 会看起来很 "正常",例如 https://example.com/user/id 十分漂亮!
不过,问题来了。由于我们的应用是一个单页的客户端应用,如果没有适当的服务器配置,用户在浏览器中直接访问 https://example.com/user/XXX,就会得到一个 404 错误。这就丑了。
你可以自定义一个我错误页面,并进行错误路由的匹配配置
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: () => import('../views/home/home.vue'),
},
{
path: '/about',
name: 'about',
},
{
path: '/:pathMatch(.*)',
name: 'error',
component: () => import('@/views/error/error.vue'),
},
],
})
export default router这样,你再去访问一个路由中不存在的页面地址,就会进入这个漂亮的错误页面了
警告
错误页面的路由配置一定要放在最下面,因为*号代表匹配所有,放在上边的话即使访问存在的页面也会将其匹配上
使用该模式进行开发,项目打包上线后会遇到刷新404的问题,需要在nginx里面进行伪静态的配置
至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。