动静路由设置个别有两种:
(1)、简略的角色路由设置:比方只波及到管理员和普通用户的权限。通常间接在前端进行简略的角色权限设置
(2)、简单的路由权限设置:比方OA零碎、多种角色的权限配置。通常须要后端返回路由列表,前端渲染应用
1、简略的角色路由设置
(1)配置我的项目路由权限
// router.js
import Vue from 'vue'import Router from 'vue-router'import Layout from '@/layout'Vue.use(Router)let asyncRoutes = [ { path: '/permission', component: Layout, redirect: '/permission/page', alwaysShow: true, name: 'Permission', meta: { title: 'Permission', roles: ['admin', 'editor'] // 一般的用户角色 }, children: [ { path: 'page', component: () => import('@/views/permission/page'), name: 'PagePermission', meta: { title: 'Page', roles: ['editor'] // editor角色的用户能力拜访该页面 } }, { path: 'role', component: () => import('@/views/permission/role'), name: 'RolePermission', meta: { title: 'Role', roles: ['admin'] // admin角色的用户能力拜访该页面 } } ] }, ]let router = new Router({ mode: 'history', scrollBehavior: () => ({ y: 0 }), routes: asyncRoutes})export default router
(2)新建一个公共的asyncRouter.js文件
// asyncRouter.js
//判断以后角色是否有拜访权限function hasPermission(roles, route) { if (route.meta && route.meta.roles) { return roles.some(role => route.meta.roles.includes(role)) } else { return true }}// 递归过滤异步路由表,筛选角色权限路由export function filterAsyncRoutes(routes, roles) { const res = []; routes.forEach(route => { const tmp = { ...route } if (hasPermission(roles, tmp)) { if (tmp.children) { tmp.children = filterAsyncRoutes(tmp.children, roles) } res.push(tmp) } }) return res}
(3)创立路由守卫:创立公共的permission.js文件,设置路由守卫
import router from './router'import store from './store'import NProgress from 'nprogress' // 进度条插件import 'nprogress/nprogress.css' // 进度条款式import { getToken } from '@/utils/auth' import { filterAsyncRoutes } from '@/utils/asyncRouter.js' NProgress.configure({ showSpinner: false }) // 进度条配置 const whiteList = ['/login'] router.beforeEach(async (to, from, next) => { // 进度条开始 NProgress.start() // 获取路由 meta 中的title,并设置给页面题目 document.title = to.meta.title // 获取用户登录的token const hasToken = getToken() // 判断以后用户是否登录 if (hasToken) { if (to.path === '/login') { next({ path: '/' }) NProgress.done() } else { // 从store中获取用户角色 const hasRoles = store.getters.roles && store.getters.roles.length > 0 if (hasRoles) { next() } else { try { // 获取用户角色 const roles = await store.state.roles // 通过用户角色,获取到角色路由表 const accessRoutes = filterAsyncRoutes(await store.state.routers,roles) // 动静增加路由到router内 router.addRoutes(accessRoutes) next({ ...to, replace: true }) } catch (error) { // 革除用户登录信息后,回跳到登录页去 next(`/login?redirect=${to.path}`) NProgress.done() } } } } else { // 用户未登录 if (whiteList.indexOf(to.path) !== -1) { // 须要跳转的路由是否是whiteList中的路由,若是,则间接条状 next() } else { // 须要跳转的路由不是whiteList中的路由,间接跳转到登录页 next(`/login?redirect=${to.path}`) // 完结精度条 NProgress.done() } }}) router.afterEach(() => { // 完结精度条 NProgress.done()})
(4)在main.js中引入permission.js文件
(5)在login登录的时候将roles存储到store中
2、简单的路由权限设置(后端动静返回路由数据)
(1)配置我的项目路由文件,该文件中没有路由,或者存在一部分公共路由,即没有权限的路由
import Vue from 'vue'import Router from 'vue-router'import Layout from '@/layout';Vue.use(Router)// 配置我的项目中没有波及权限的公共路由export const constantRoutes = [ { path: '/login', component: () => import('@/views/login'), hidden: true }, { path: '/404', component: () => import('@/views/404'), hidden: true },] const createRouter = () => new Router({ mode: 'history', scrollBehavior: () => ({ y: 0 }), routes: constantRoutes})const router = createRouter() export function resetRouter() { const newRouter = createRouter() router.matcher = newRouter.matcher} export default router
(2)新建一个公共的asyncRouter.js文件
// 引入路由文件这种的公共路由import { constantRoutes } from '../router';// Layout 组件是我的项目中的主页面,切换路由时,仅切换Layout中的组件import Layout from '@/layout';export function getAsyncRoutes(routes) { const res = [] // 定义路由中须要的自定名 const keys = ['path', 'name', 'children', 'redirect', 'meta', 'hidden'] // 遍历路由数组去重组可用的路由 routes.forEach(item => { const newItem = {}; if (item.component) { // 判断 item.component 是否等于 'Layout',若是则间接替换成引入的 Layout 组件 if (item.component === 'Layout') { newItem.component = Layout } else { // item.component 不等于 'Layout',则阐明它是组件门路地址,因而间接替换成路由引入的办法 newItem.component = resolve => require([`@/views/${item.component}`],resolve) // 此处用reqiure比拟好,import引入变量会有各种莫名的谬误 // newItem.component = (() => import(`@/views/${item.component}`)); } } for (const key in item) { if (keys.includes(key)) { newItem[key] = item[key] } } // 若遍历的以后路由存在子路由,须要对子路由进行递归遍历 if (newItem.children && newItem.children.length) { newItem.children = getAsyncRoutes(item.children) } res.push(newItem) }) // 返回解决好且可用的路由数组 return res}
(3)创立路由守卫:创立公共的permission.js文件,设置路由守卫
// 进度条引入设置如下面第一种形容一样import router from './router'import store from './store'import NProgress from 'nprogress' // progress barimport 'nprogress/nprogress.css' // progress bar styleimport { getToken } from '@/utils/auth' // get token from cookieimport { getAsyncRoutes } from '@/utils/asyncRouter' const whiteList = ['/login'];router.beforeEach( async (to, from, next) => { NProgress.start() document.title = to.meta.title; // 获取用户token,用来判断以后用户是否登录 const hasToken = getToken() if (hasToken) { if (to.path === '/login') { next({ path: '/' }) NProgress.done() } else { //异步获取store中的路由 let route = await store.state.addRoutes; const hasRouters = route && route.length>0; //判断store中是否有路由,若有,进行下一步 if ( hasRouters ) { next() } else { //store中没有路由,则须要获取获取异步路由,并进行格式化解决 try { const accessRoutes = getAsyncRoutes(await store.state.addRoutes ); // 动静增加格式化过的路由 router.addRoutes(accessRoutes); next({ ...to, replace: true }) } catch (error) { // Message.error('出错了') next(`/login?redirect=${to.path}`) NProgress.done() } } } } else { if (whiteList.indexOf(to.path) !== -1) { next() } else { next(`/login?redirect=${to.path}`) NProgress.done() } }}) router.afterEach(() => { NProgress.done()})
(4)在main.js中引入permission.js文件
(5)在login登录的时候将路由信息存储到store中
// 登录接口调用后,调用路由接口,后端返回相应用户的路由res.router,咱们须要存储到store中,不便其余中央拿取this.$store.dispatch("addRoutes", res.router);
到这里,整个动静路由就能够走通了,然而页面跳转、路由守卫解决是异步的,会存在动静路由增加后跳转的是空白页面,这是因为路由在执行next()时,router外面的数据还不存在,此时,你能够通过window.location.reload()来刷新路由
后端返回的路由格局:
routerList = [ { "path": "/other", "component": "Layout", "redirect": "noRedirect", "name": "otherPage", "meta": { "title": "测试", }, "children": [ { "path": "a", "component": "file/a", "name": "a", "meta": { "title": "a页面", "noCache": "true" } }, { "path": "b", "component": "file/b", "name": "b", "meta": { "title": "b页面", "noCache": "true" } }, ] }]
留神:vue是单页面应用程序,所以页面一刷新数据局部数据也会跟着失落,所以咱们须要将store中的数据存储到本地,能力保障路由不失落。对于vue页面刷新保留页面状态,
1、通过本地存储 state中的数据,页面刷新胜利后再次从本地存储中读取state数据
// vuex中的数据产生扭转时触发localStorage的存储操作localstorage.setItem('state', JSON.stringify(this.$store.state)) // 页面加载的时候在created中获取本地存储中的数据localStorage.getItem('state') && this.$store.replaceState(JSON.parse(localStorage.getItem('state')));
留神:该操作会频繁的触发localStorage的存取工作
2、 监听页面刷新,触发存取操作
首先在入口组件App.vue中的created中利用localstorage或者sessionStorage来存取state中的数据
// 在页面加载时读取sessionStorage里的状态信息 if ( sessionStorage.getItem('state') ) { this.$store.replaceState( Object.assign( {}, this.$store.state, JSON.parse(sessionStorage.getItem('state') ) ) )} // 页面刷新时将state数据存储到sessionStorage中 window.addEventListener('beforeunload',()=>{ sessionStorage.setItem('state',JSON.stringify(this.$store.state) )})
留神:Object.assign() 办法用于将所有可枚举属性的值从一个或多个源对象复制到指标对象
到这里,咱们在PC端、安卓端、mac端safair浏览器中均能失常拜访,然而在ios端的safair浏览器中存在问题,页面刷新后拿不到数据。
起因:在ios端beforeunload办法未执行,造成state数据未存储到本地,通过查问ios官网文档,文档中说unload和beforeunload曾经废除,应用pagehide作为代替
window.addEventListener('pagehide', () => { sessionStorage.setItem('state', JSON.stringify(this.$store.state)) })
这样一番改变后,果然在PC端、安卓端、ios端均未呈现问题
// 会话历史事件
pageshow事件:在用户拜访页面时触发;pageshow 事件相似于 onload 事件,onload 事件在页面第一次加载时触发, pageshow 事件在每次加载页面时触发,即 onload 事件在页面从浏览器缓存中读取时不触发。 pagehide事件:在用户来到以后网页时触发;pagehide 事件有时能够代替 unload事件,但 unload 事件触发后无奈缓存页面。