vue router实现登录拦截的详细步骤
时间: 2023-08-02 10:14:40 浏览: 39
Vue Router 可以通过导航守卫(Navigation Guards)来实现登录拦截,以下是详细步骤:
1. 在路由配置中设置需要拦截的路由,比如需要登录才能访问的页面:
```javascript
const routes = [
{
path: '/',
component: Home
},
{
path: '/login',
component: Login
},
{
path: '/profile',
component: Profile,
meta: {
requiresAuth: true // 需要登录才能访问
}
}
]
```
2. 在路由实例中定义全局前置守卫(beforeEach),判断用户是否已经登录:
```javascript
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
const isAuthenticated = store.getters.isAuthenticated
if (requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
```
3. 在 Vuex 中定义一个 isAuthenticated 状态,用来判断用户是否已经登录:
```javascript
const store = new Vuex.Store({
state: {
isAuthenticated: false
},
mutations: {
login (state) {
state.isAuthenticated = true
},
logout (state) {
state.isAuthenticated = false
}
},
getters: {
isAuthenticated: state => state.isAuthenticated
}
})
```
4. 在登录成功后,调用 Vuex 中的 login mutation 修改 isAuthenticated 状态:
```javascript
methods: {
login () {
this.$store.commit('login')
this.$router.push('/profile')
}
}
```
这样,当用户访问需要登录才能访问的页面时,会先执行全局前置守卫,判断用户是否已经登录,如果未登录则重定向到登录页面;如果已经登录,则继续访问页面。同时,登录成功后会调用 Vuex 中的 login mutation 修改 isAuthenticated 状态,从而实现登录拦截的功能。