思路
菜单重定向 在route中写好公用方法~
但是初次加载的时无菜单列表
所以我们在path为’/'时 初始化的首页定向 写在页面layout中
同时加入登录前后需要记录返回的页面historyBack
和无权限页面noRight
的判断显示~
实现
路由route
大致如下
重点为redirectTo
方法
返回结果为该菜单对应有权限的第一个子菜单 递归多级菜单查找~
import Vue from 'vue'
import Router from 'vue-router'
import utils from '@/common/utils'
import store from '../store'
Vue.use(Router)
let route = new Router({
routes: [
{path: '/login',name: 'login',component: () => import('@/pages/login')},
{
path: '/',
name: 'layout',
component: () => import('@/pages/layout'),
children: [
{path: '/noRight',component: () => import('@/pages/noRight')},
{
path: '/aaa',
component: () => import('@/pages/aaa/index'),
redirect: () => { return redirectTo('/aaa') },//重定向设置到aaa对应有权限的第一个子菜单
children: [
{path: '/aaa/a',component: () => import('@/pages/aaa/a')},
{path: '/aaa/b',component: () => import('@/pages/aaa/b')}
]
}
]
},
})
let children = []
const redirectTo = path => {
let menuArr = store.getters.menuList
if (menuArr) {
getChildren(menuArr, path)
if (children && children.length) return children[0].url
else return undefined
}
else return undefined
}
const getChildren = (list, menuUrl = '') => {
list.forEach(item => {
if (item.url === menuUrl) {
children = item.childrens
children = children[0] ? children : [item]
} else {
let firstList = item.childrens
getChildren(firstList, menuUrl)
}
})
}
// 导航守卫 记录初始化页面链接
route.beforeEach((to, from, next) => {
console.log('from', from.path, '---------to', to.path)
if (from.path === '/' && to.path !== '/' && to.path !== '/login' && to.path !== '/noRight') {
!utils.getSS('historyBack') && utils.setSS('historyBack', to.path)
}
next()
})
layout的method方法
加载完菜单后调用menuRedirect
(另外在watch的’$route.path’也调用menuRedirect
用于跳转链接是否有权限)
menuRedirect () {
let menuList = utils.getLS('menuList')
let noRightList = utils.getLS('noRightList')
let toPath = this.$route.path
if (this.$route.path === '/') { // 初始化的重定向
let historyBack = utils.getSS('historyBack')
if (historyBack && historyBack !== '/' && historyBack !== '/noRight') {
console.log('记录的返回页跳转', historyBack)
if (!noRightList.includes(historyBack)) {
toPath = historyBack
this.$router.replace(toPath)
} else {
toPath = '/noRight'
this.$router.replace(toPath)
}
utils.setSS('historyBack', '')
} else {
console.log('正常菜单首页跳转')
toPath = this.$route.path !== menuList[0].res_url ? menuList[0].res_url : toPath
this.$route.path !== toPath && this.$router.replace(toPath)
}
}
// 新定向页是否有权限
let paths = toPath.split('/')
if (!menuList || !menuList.length || noRightList.includes(toPath) ||
(paths[1] && noRightList.includes([paths[0], paths[1], 'index'].join('/'))) ||
(paths[2] && noRightList.includes([paths[0], paths[1], paths[2], 'index'].join('/'))) ||
(paths[3] && noRightList.includes([paths[0], paths[1], paths[2], paths[3], 'index'].join('/')))
) {
this.$router.replace('/noRight')
}
}