1. Vue Route 全局前置守卫
Vue Route的详细文档地址为:Vue Route
Vue Route 全局前置守卫是每次页面跳转之前执行的函数,函数详情为:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。
每个守卫方法接收三个参数:
-
to: Route: 即将要进入的目标 路由对象
-
from: Route: 当前导航正要离开的路由
-
next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
next(’/’) 或者 next({ path: ‘/’ }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: ‘home’ 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
确保要调用 next 方法,否则钩子就不会被 resolved。
2. 使用Vue Route管理页面跳转
首先在定义路由时配置 meta 字段,例如:
routes: [
path: '/MainPage',
name: 'MainPage',
component: MainPage,
meta: { requiresAuth: true }
]
然后再前置守卫访问:
router.beforeEach((to, from, next) => {
//判断访问的页面是否有requiresAuth字段
if (to.matched.some(record => record.meta.requiresAuth)) {
// 如果未登录,则跳转到登录页面
// 否则正常跳转
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 确保一定要调用 next()
}
})
3. 使用导航守卫管理页面跳转以及同步前后端登录状态
同步前后端登录状态所使用的方法就是在前置守卫中访问后端接口,检查是否登录,这样在每次跳转时前后端都会同步登录状态。
下面代码使用前置守卫同步前后端登录状态,并设置当用户已登录时无法跳转到规定页面,即登录注册等页面。
router.beforeEach((to, from, next) => {
var url = "/api/users/checkStatus";
//检查登录状态
Vue.http.get(url).then(function(res){
Vue.cookies.set("id", res.body.id);
//跳转回主页面
if (to.matched.some(record => record.meta.notNeedAuth)) {
next({name: 'MainPage',})
}
//跳转
else {
next()
}
},function(res){
//无登录状态
if (res.status == '400') {
if (Vue.cookies.isKey("id")) {
Vue.cookies.remove("id")
}
}
next()
});
})