因为所以
Vue.router有2种路由模式 history和 hash.hash模式会将浏览器地址以#分割开,比如 /admin/blog/#blog/list, 非常不好看. 由于博客是将VUE项目通过Nginx挂载到非根目录的.所有搜索了一圈
第一步 修改为History模式
根据GitHub上ru23的处理我设置了
nginx.conf 给 try_files 增加目录 dist表示你的文件位置
location /blog/ {
index index.html index.htm index.php;
try_files $uri $uri/ /dist/index.html;
}router.js
new Router({
mode: 'history',
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes //我的路由细节
})vue.config.js
module.exports = {
publicPath: '/admin',
}整个从界面操作流程都ok了 但是有2个问题 1.当我访问比如 /blog/detail/2 时,进入了404. 2.GitHub上ru23的处理他给所有的路由都增加了一个挂载路径的前缀,太过麻烦
routes: [{
path: '/teacher/login',
name: 'Login',
component: Login,
meta: {
title: '教师端登录中心'
}
}, {
path: '/teacher/courseCenter',
name: 'CourseCenter',
component: CourseCenter,
meta: {
title: 'CourseCenter'
}
}]我觉这样不方便,特别是在嵌套路由的情况下.
第二步 路径前缀
搜了一圈发现可以给 router增加一个base参数
router.js
new Router({
mode: 'history',
base: '/admin', //挂载的路径
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes //我的路由细节
})应该是VUE 在GitHub上ru23的处理之后加上的属性.
事已至此 已经简化了许多
第三步 通过vue-cli的环境变量进行配置
项目根目录下创建并写入环境变量文件
.env.development
# 开发模式项目的挂载地址
VUE_APP_BASE='/admin-dev' .env.production
#发布模式的挂载地址
VUE_APP_BASE='/admin'router.js 配置路由
const routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
new Router({
mode: 'history',
base: process.env.VUE_APP_BASE, //挂载的路径
scrollBehavior: () => ({ y: 0 }),
routes: routes //我的路由细节
})vue.config.js 配置vue
module.exports = {
publicPath: process.env.VUE_APP_BASE,
}注意环境变量必须以 VUE_APP_开头
*npm run dev 运行时,
process.env.VUE_APP_BASE 表示 /admin-dev
运行 npm run build 打包的文件
process.env.VUE_APP_BASE 表示 /admin-dev
*
结束