全局守卫
全局守卫我们用beforeEach函数
const router = new VueRouter({
routes:[
{
name:"Home",
path:"/Home",
component:Home,
props:true,
children:[
{
path:"Circle",
component:Circle
},
{
path:"Foucs",
component:Foucs
}
]
},
{
path:"/About",
component:About
}
]
})
router.beforeEach((to,from,next)=>{
console.log(to)
})
代码中我们输出to、from和next,然后我们点击首页查看输出,发现to为要跳转的路由,from是当前的路由,next是跳转的函数

接下来我们可以通过给路由配置的meta参数来控制是否可以跳转
const router = new VueRouter({
routes:[
{
name:"Home",
path:"/Home",
component:Home,
props:true,
meta:{
canJump:true
},
children:[
{
path:"Circle",
component:Circle
},
{
path:"Foucs",
component:Foucs
}
]
},
{
path:"/About",
component:About,
meta:{
canJump:false
}
}
]
})
router.beforeEach((to,from,next)=>{
if(to.meta.canJump){
next()
}else{
alert("不可跳转")
}
})

独享守卫
就是在配置路由的时候给路由加入beforeEnter函数
const router = new VueRouter({
routes:[
{
name:"Home",
path:"/Home",
component:Home,
props:true,
meta:{
canJump:true
},
children:[
{
path:"Circle",
component:Circle
},
{
path:"Foucs",
component:Foucs
}
]
},
{
path:"/About",
component:About,
//独享守卫
beforeEnter(to,from,next){
alert("不可跳转")
},
meta:{
canJump:false
}
}
]
})
组件守卫
组件内可以通过beforeRouteEnter和beforeRouteLeave来监控路由的跳转进来和跳转出去
<script>
export default {
data(){
return {
num:0
}
},
methods: {
add() {
this.num++
}
},
beforeRouteEnter(to,from,next){
console.log("进入")
next()
},
beforeRouteLeave(to,from,next){
console.log("离开")
next()
}
}
</script>

网友评论