赞
踩
把路由表的数据结构和后端沟通好,然后后端把对应权限的路由树给前端返回,前端在vuex中处理处理路由
import Cookies from 'js-cookie' import router from '@/router' import userInfos from '@/api/login' import date from '../modules/user' const Layout = () => import ('@/layout') // 全局组件 const _import = require('@/router/_import_' + process.env.NODE_ENV) const state = { routers: sessionStorage.getItem('navRouters') ? sessionStorage.getItem('navRouters') : [], navRouters: sessionStorage.getItem('navRouters') ? sessionStorage.getItem('navRouters') : [], } const mutations = { // 菜单权限 SET_ALL_MENU_LIST(state, menulist) { state.navRouters = menulist state.routers = menulist } }
onst actions = { // 菜单获处理 setAllMenuList({ commit }, userInfo) { /** * 初始化路由 * @param router 路由文件,是一个数组 */ function initRouter(router) { for (let i = 0; i < router.length; i++) { const route = router[i] // 设置一级路由的控件为全局定义的默认控件 route.component = Layout // 设置子路由 route.children && initChildrenRouter(route.children) } return router } /** * 初始化子路由 * @param router 子路由数组 */ function initChildrenRouter(router) { for (let i = 0; i < router.length; i++) { const route = router[i] // 初始化子路由的控件 route.component && (route.component = _import(route.component)) route.children && route.children.length && initChildrenRouter(route.children) } } return new Promise((resolve, reject) => { userInfos .postGetUserRoutes(date.state.userId) .then(response => { const { result, code } = response if (code === 200) { if (result.length) { result.forEach(v => { for (let i = 0; i < v.children[0].children.length; i++) { if (!v.children[0].children[i].hidden === true) { v.redirect = v.path + '/' + v.children[0].path + '/' + v.children[0].children[i].path break } } }) } const accessedRouters = initRouter(result) console.log('accessedRouters', accessedRouters) accessedRouters.push({ path: '*', redirect: '/404', hidden: true }) router.addRoutes(accessedRouters) sessionStorage.setItem( 'navRouters', JSON.stringify(accessedRouters) ) sessionStorage.setItem( 'allMenuList', JSON.stringify(accessedRouters) ) commit('SET_ALL_MENU_LIST', accessedRouters) resolve() } else { reject(response.data) } }) .catch(error => { reject(error) }) }) } }
为了防止刷新丢失,在路由守卫中要加一层条件
const hasGetUserInfo = store.getters.name if (hasGetUserInfo) { // 处理最新路由 console.log('00', to) if (!isAddTrue) { isAddTrue++ store.dispatch('app/setAllMenuList', '').then(() => { console.log('00', to) next({ path: to.path }) }) } else { next() } } else { try { // get user info await store.dispatch('user/getInfo') next() } catch (error) { // remove token and go to login page to re-login await store.dispatch('user/resetToken') Message.error(error || 'Has Error') next(`/login?redirect=${to.path}`) NProgress.done() } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。