定义路由的时候可以配置 meta字段,给路由加特定的标识。
示例
router:new VueRouter({
routes:[{
path:"/",
component:Index
},{
path:"/shopCar",
component:ShopCar,
meta:{
// 是否需要登录验证
login:true
}
}]
}),
watch:{
"$route"(to){
// 路由切换拦截
if(to.path=="/shopCar"||to.path=="/personal"){
if(to.meta.login){
if(!this.$store.state.login){
this.$router.push("/login?url="+to.fullPath);
}
}
}
}
当用户点击购物车时,需要先通过meta来判断是否需要登陆验证,如果表示为真,说明需要在登录状态下才能查看,会检查用户状态是否登录,未登录时可以设置直接跳到登录页,当登陆时再通过to.fullPath跳到购物车界面。