用户不登陆也可以查看的页面
// router index.js
export const constantRouterMap = [
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [{
path: 'dashboard',
component: () => import('@/views/dashboard/index'),
name: 'Dashboard',
meta: { title: '首页', icon: 'home', noCache: true }
}]
},
{
path: '/404', component: Layout, hidden: true,
children: [{
path: '',
component: () => import('@/views/404')
}]
},
{
path: '/login',
// component: Layout,
hidden: true,
name: 'login',
component: () => import('@/views/login/index')
}
]
export const createRouter = () => new Router({
// mode: 'history',
routes: constantRouterMap
})
// 重置上一次的matcher,用户退出后不刷新页面,重置router里的routes
const router = createRouter()
export default routerVuex设置
由于this.$options.routes非响应式,因此我们需要将所有的路由放到vuex中,动态渲染菜单
路由放入state中
state: {
routes: constantRouterMap, // 静态路由 router index.js
addRoutes: [] // 动态匹配的路由
}在action中过滤路由
// 生成路由
generatorRoutes({ commit }, roles) {
return new Promise((resolve, reject) => {
addRoutes = asyncRoutes.filter(route => roles.find(item => item === route.role))
commit('SET_ROUTES', addRoutes) // 提交处理好的路由放到state中
resolve(addRoutes)
})生成动态路由
当前用户可以查看的页面
router.beforeEach((to, from, next) => {
// 获取cookie中的token
const hasRole = getRole()
if (hasRole && hasRole !== 'undefined') {
// 当vuex中没有路由时,开始生成路由
if (!store.getters.addRoutes.length) {
// 获取当前用户可以查看的页面role
store.dispatch('getUserRole', JSON.parse(hasRole)).then(res => {
if (res.length) {
// generator Routes
store.dispatch('generatorRoutes', res).then(addRoutes => {
// 清除上一次保存的路由
router.matcher = createRouter().matcher
// 通过 addRoutes添加过滤好的路由
router.addRoutes(addRoutes.concat([{ path: '*', redirect: '/404', hidden: true }]))
next({ ...to, replace: true })
})
} else {
// if response is empty jump to login router
removeCookies()
next({ path: '/login' })
}
}).catch(() => {
removeCookies()
next({ path: '/login' })
})
} else {
if (whiteList.indexOf(to.path) > -1) {
next('/dashboard')
} else {
next()
}
}
} else {
removeCookies()
if (whiteList.indexOf(to.path) > -1) {
next()
} else {
next({ path: '/login' })
}
}
})打工者联盟为了抵抗996、拖欠工资、黑心老板、恶心公司,让我们组成打工者联盟。客观评价自己任职过的公司情况,为其他求职者竖起一座引路的明灯。https://book.employleague.cn/
版权声明:本文为yin_you_yu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。