vue2路由守卫代码实例
时间: 2023-11-06 21:07:50 浏览: 37
以下是一个基本的vue2路由守卫代码示例:
```javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{
path: '/',
component: Home
},
{
path: '/about',
component: About,
meta: {
requiresAuth: true // 需要登录才能访问该页面
}
}
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) { // 判断该路由是否需要登录权限
if (localStorage.getItem('token')) { // 判断当前用户的登录状态是否存在
next()
} else {
next({
path: '/login',
query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
} else {
next()
}
})
export default router
```
在这个例子中,我们使用了`beforeEach`路由守卫来判断用户是否登录以及是否有权限访问该页面。如果用户需要登录才能访问该页面,则会检查当前用户的登录状态是否存在。如果用户未登录,则会将用户重定向到登录页面,并将跳转的路由path作为参数传递给登录页面。登录成功后,用户将被重定向到原始请求的路由。如果用户已经登录或者该页面不需要登录,则直接访问该页面。