路由守卫主要的用途是处理页面路由的跳转,在某些特殊的页面可以对路由的跳转进行拦截,比如:淘宝网的订单列表页面,如果用户没有登录,那么是根本无法查看订单列表的,这时就需要将页面指向登录页提示用户登录,这种情况就需要做路由守卫去检测跳转的那个目标路由。
1、全局路由
在router.js路由文件中处理
const user = {
login(){
return sessionStorage.getItem('token') ? true : false;
}
}
router.beforeEach((to,from,next)=>{
if(to.path == '/'){
// 进入首页前进行拦截,判断是否带有token值
if(user.login()){
// 返回true表示有token值
next(); //让他进入
}else{
next('/login'); //让他返回到登录页
}
}else{
next();
}
})
1、组件内路由守卫(局部路由)
组件内使用路由守卫,此时,Vue组件实例并未初始化,这个时候,在路由守卫beforeRouteEnter
中是拿不到组件实例的this
的 !,路由守卫主要的用途是做路由的拦截用的,它的执行优先于组件生命周期的开始。
advance.vue组件的代码:
<script>
export default {
name: "cinema",
beforeRouteEnter(to, from, next) {
let hasId = sessionStorage.getItem("filmId") ? true : false;
if (hasId) {
// 当拿到了电影的id,执行组件实例化
next(); //放行
} else {
alert('filmId error!') //跳转到对应的路由页面处理逻辑
}
},
data() {
return {
filmId: "",
filmName: "",
};
},
mounted() {
// 获取hash值
console.log(this.$route);
this.filmId = this.$route.params.id;
this.filmName = this.$route.params.name;
},
};
</script>