注:要进行下一步操作一定要加next()方法哦!!!
1、全局路由守卫
router.beforeEach((to, from, next) => {
if(to.meta.auth) {
if(window.isLogin) {
next();
} else {
next('/login?redirect=' + to.fullPath)
}
} else {
next();
}
});
2、局部路由守卫 【进入路由时】 (注:写在router具体路由的配置中)
beforeEnter: ((to, from, next) => {
if (window.isLogin) {
next();
} else {
next('/login?redirect=' + to.fullPath)
}
});
3、组件路由守卫 (注:写在组件中,和data(){}方法平级的任意位置)
- A、组件路由守卫 之 进入路由时,【组件实例还没渲染,this还不能用哦,要用next((vc)=>{})回调函数传回来的 vc === VueComponent】
beforeRouteEnter(to, from, next) {
next(vc => {
console.log(vc);
vc.id = vc.$route.params.id;
if (vc.id) {
vc.getUserInfo();
}
});
},
- B、组件路由守卫 之 变化路由时,【组件实例已渲染,this可用】
beforeRouteUpdate(to, from, next) {
console.log("路由发生变化了!");
next();
},
- C、组件路由守卫 之 离开路由时,【组件实例已渲染,this可用】
beforeRouteLeave(to, from, next) {
console.log(to.fullPath);
next();
},