背景
vue 项目中如果使用 vue-router 的话避免不了历史模式的选择,那么如何选择合适的历史模式
hash 模式
hash 模式是 vue-router 的默认模式,路径后面会携带一个 #,然后才是路径。正式因为这个#符号是的路径变化不会触发页面重新加载
http://location:3000/#/page1
HTML5 模式
这个是我们熟悉的模式,路径跳转则进入对应的页面。vue是单页面,需要避免这种跳转而进行服务器的配置
nginx 服务器配置拦截,即任何当前域名的地址访问都匹配到默认的页面
如果项目部署在域名下的文件夹中,例如test文件夹
server
{
location / {
try_files $uri $uri/ /index.html
}
# 访问 /test/* 的文件不存在则进入 /test/index.html
location /test/ {
try_files $uri $uri/ /test/index.html
}
}
vue2 vue3 历史模式的变更
// vue2
const pathname = window.location.pathname
const router = new Router({
mode: 'history',
base: pathname
})
// vue3
import { createRouter, createWebHistory } from 'vue-router'
const pathname = window.location.pathname
const router = createRouter({
history: createWebHistory(pathname)
})
- new Router 变成 createRouter
- history 配置取代 mode
- 改变 base 配置位置
两种模式没变化,主要是写法上的变更。这里让我想到了 new Vue() 实例化到现在的 createApp()
这里有一个小技巧,路由的 base 可以设置成 window.location.pathname,这样就可以随着网站链接的变化而变化了
总结
- hash模式会额外的在url中添加#
- HTML5模式利用服务器配置拦截跳转达到和#相同的作用
- 当项目部署在域名下的文件夹时,需要特殊处理。即 重定向 & base 路径
思考
- 两种历史模式的概念
- 比较优缺点