1.航行守卫草图。..NavigationGuard就像校门口的保安。模拟从家到学校的过程。持有学生证,方可进入学校;没有学生证或遗失学生证的,可补办学生证入校;拦截器,满足条件跳转,不满足条件取消。1.1GlobalGuard1.1.1beforeEachrouter.js:importVuefrom"vue"importVueRouterfrom"vue-router"importHomefrom"../components/home.vue"Vue.use(VueRouter)constrouter=newVueRouter({模式:'历史',路线:[{路径:'/',组件:{默认:主页,haveName:()=>导入(“../components/haveName.vue”),},},{路径:'/new',component:()=>import("../components/new.vue"),},],})router.beforeEach((to,from,next)=>{console.log(to)console.log(from)next()})exportdefaultrouter看看效果:to:whereareyougoing?来自:你来自哪里?那么next()是做什么的呢?简单的说就是控制跳跃和取消。执行next()可以跳转,执行next(false)则不能跳转。守卫也可以控制点击后跳转到指定路径,例如:router.beforeEach((to,from,next)=>{if(to.path=='/article'){next('/new')alert("Ishouldbe'/article'")}else{next()}})看效果:1.1.2beforeResolve和上面基本一样,不同的是执行时间更晚了:1.1.3afterEach1.2Route专属守卫另一个草图。..与全局守卫不同,路由独占守卫是指守卫只在跳转到指定路径时才会出现:它只有一个钩子函数,beforeEnter:例如:{path:'/about',component:()=>import("../components/about.vue"),beforeEnter:(to,from,next)=>{console.log(to)console.log(from)next()},},effect:router只有守卫在.js中为/about添加,所以只有在切换路由时输入/about才会触发守卫。1.3In-componentguards不同于globalguards和route-onlyguards。组件防护意味着组件所在的路径将被防护。1.3.1beforeRouteEnter:hot.vue:
