Vue路由:Vue Router文档
路由基础配置:
- 使用路由需要先通过命令加入依赖
- npm install --save vue-router
- 创建路由配置文件:
// 引入相关文件 import Vue from 'vue'; import Router from 'vue-router'; // 添加路由元素 import Home from '@/components/Home'; const router = new Router({ //开启history模式 mode: 'history', // 设置history模式项目根路径名称 base: '/项目访问时的路径', routes: [ { path: '/',// 路由展示的地址 name: 'Home',//路由名称 component: Home,// 引入的路由实例对象 meta: {// 路由附加属性 requiresAuth: true }, // 单个路由的钩子方法 beforeEnter: (to, from, next) => { next(); } }, ] }); // 所有路由的钩子方法 router.beforeEach((to, from, next) => { // 验证路由的附加属性 if (to.matched.some(record => record.meta.requiresAuth)) { next(); } }); // 使用路由 Vue.use(Router); // 返回路由对象 export default router;
- 在 main.js 中将路由设置为Vue对象的组件
- 引入router 对象的js文件:import router from ‘./router/index’;
- 在 vue 对象中加入 router
Vue项目访问地址如何去掉 # 符号:
Vue history模式:
-
路由中需要开启 history模式
//在路由配置的 Router 对象中的 routes 前添加以下内容 //开启history模式 mode: 'history', // 设置history模式项目根路径名称 base: '/project-name'
-
配置 webpack.prod.conf.js打包文件:
- 在 output属性 中添加访问域名属性 publicPath: http://你的域名
-
配置Nginx反向代理:
location /project-name { // root为项目在Nginx的目录,截止到项目文件夹为止 root /项目在Nginx中的根路径/; // 项目文件夹到主页的index.html完整路径 try_files $uri $uri/ /project-name/index.html; // 强制设定主页文件夹地址 index index.html; }
-
主页访问地址为:http://你的域名/project-name
-
路由访问地址为:http://你的域名/project-name/路由path