vue路由拦截和nuxt中间件拦截

通过路由拦截实现登陆权限的控制,在vue中,通过在路由元信息meta中设置实现拦截。

设置roles,表示能够访问页面的具体用户,访问页面时触发导航守卫router.beforeEach,判断当前访问的用户是否包含时roles里。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
路由设置
routes: [
{
path: '/login',
name: 'login',
meta: {
roles: ['admin', 'user']
},
component: () => import('../components/Login.vue')
},
{
path: 'home',
name: 'home',
meta: {
roles: ['admin']
},
component: () => import('../views/Home.vue')
},
]
页面控制
//从后端获取当前用户
const role = 'user'
//触发导航守卫 router.beforeEach
router.beforeEach((to,from,next)=>{
if(to.meta.roles.includes(role)){
next() //放行
}esle{
next({path:"/404"}) //跳到404页面
}
})

或者在meta中设置requireAuth属性,然后遍历route.match来检查meta的requireAuth属性,进行判断。

在nuxt中,由于是同构渲染,对于服务端而言,要在进入页面前进行拦截,nuxt提供中间件实现服务端和客户端的在页面渲染之前对页面进行拦截。

查看评论