vue的路由有两种模式,默认为 hash模式,还有一种为 history 模式,这两种模式显式的最大区别是,浏览器地址栏 hash 模式在末尾带有 # ,而 history 模式不带 #。下面介绍两种模式的配置(在vue-cli3.x下创建的项目)。
有三个地方需要配置,一个是 vue.config.js,一个是 router/index.js,一个是 nginx 线上部署配置。
hash 模式
- vue.config.js 配置配置 publicPath 为 “./”
- router/index.js 配置mode 修改为 “history”
- nginx 线上部署
location /xxx{
root E:/nginxVueApps/;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
# 注:xxx为打包后的项目名称
- 访问
localhost:8080/xxx
最终浏览器地址栏的 url 为 localhost:8080/xxx/#/,也就是 hash 模式会带有 #
history 模式
- vue.config.js 配置配置 publicPath 为 “/xxx”
- router/index.js 配置mode 修改为 “history”
- nginx 线上部署
location /xxx{
root E:/nginxVueApps/;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
# 注:xxx为打包后的项目名称,在 vue.config.js 的配置中
# 要将 publicPath 配置为 "/打包后的项目名称",否则打包后访问页面为空白
- 访问
localhost:8080/xxx最终浏览器地址栏的 url 为 localhost:8080/xxx,也就是 history 模式不会带有还有一点。
注意
需要注意的是 history 模式如果直接在浏览器里面输入路由里的访问地址,页面还是会空白的,需要使用 router 的跳转,如在理由里面配置了一个页面
{
// operation
path: '/o',
name: 'Operation',
component: () => import('../components/Operation')
},
上线部署后,如果直接在浏览器里面输入 localhost:8080/xxx/o,这样的页面是空白的,需要使用跳转的方法,如
this.$router.push(
{
path: '/o',
})
这样才能正常访问