一、起步
1、概念
Vue Router 是 Vue.js官方的路由管理器,主要用来做SPA(Single Page Application),单页面应用”
路由模式:
- hash:历史模式,不会制造页面刷新
- history:不会有历史,不会制造页面刷新
2、安装
npm install vue-router
yarn add vue-router
二、配置Router
1、搭建路由文件
位置:src/router/index.js
1、引用文件
import vue from 'vue'
import vueRouter from 'vue-router'
vue.use(vueRouter)
// 导入模板文件(用于公共路由)
import user from './modules/user'
import system from './modules/system';
// 导入公共页面(用于component)
import Layout from '@/layout/index.vue'
import Redirect from '@/views/redirect/redirect.vue'
import Page404 from '@/views/404/404'
// 定义动态路由
const dynamicRoutes= [
...user,
...system
]
// 定义公共路由
const getPublicRoutes = () => {
return [
{
path: '/',
name: 'Layout',
component: Layout,
meta: {
title: 'layout' },
redirect: '/redirect',
children: [
{
path: '/redirect/:path*',
name: 'Redirect',
component: Redirect,
meta: {
title: '重定向' }
},
{
path: '/404',
name: 'Page404',
component: Page404,
meta: {
title: '404' }
}
]
},
{
path: '/login',
name: 'Login',
component: () => import('@/views/login/login.vue'),
meta: {
title: '登录 ' }
},
{
path: '*',
redirect: '/404'
}
]
}
// 创建路由
const createRouter = (routes) => new VueRouter({
scrollBehavior: () => ({
y: 0 }),
routes: routes
});
const router = createRouter(getPublicRoutes());
// 重置路由
export const resetRouter = (routes) => {
const newRouter = createRouter(routes || getPublicRoutes());
router.matcher = newRouter.matcher;
};
导出,将Router对象传入到vue实例
export default router
2、配置路由权限控制
位置:src/router/router.js
作用:进行路由导航守卫配置, 通过VueX数据对登录者的状态进行判断
import AppConfig from "@/config/app-config"; // 导入全局配置
import router from "@/router/index";
import store from "@/store/index";
import NProgress from "nprogress"; // 引入 进度条:页面跳转时出现在浏览器顶部的进度条
import "nprogress/nprogress.css"; // 引入 进度条样式
NProgress.configure({
showSpinner: false }); // 禁用进度环
// 全局前置守卫
router.beforeEach((to, from