Vue项目中登陆权限拦截
时间: 2024-04-29 15:21:25 浏览: 8
在 Vue 项目中,可以使用路由守卫来实现登陆权限拦截。具体步骤如下:
1. 在路由配置文件中,给需要登陆后才能访问的路由设置 meta 属性,例如:
```
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: { requiresAuth: true }
}
```
2. 在全局导航守卫中判断路由的 meta 是否需要认证,如果需要认证,则判断用户是否已经登陆。如果已经登陆,则放行;否则跳转到登陆页面。示例代码:
```
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.state.isLoggedin) { // 判断用户是否已经登陆
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
```
上面代码中的 `store.state.isLoggedin` 表示用户是否已经登陆的状态,需要根据具体的业务逻辑进行修改。
3. 在登陆成功后,将用户的登陆状态保存到 Vuex 或者 localStorage 中。示例代码:
```
// 登陆成功后
store.commit('setLoggedin', true) // 将用户登陆状态保存到 Vuex 中
localStorage.setItem('isLoggedin', true) // 将用户登陆状态保存到 localStorage 中
```
上面代码中的 `setLoggedin` 是一个 Vuex mutation,用来更新用户登陆状态的。
通过以上步骤,即可在 Vue 项目中实现登陆权限拦截。