Vue导航守卫

    技术2022-07-11  77

    导航守卫(中间件)

    全局守卫

    路由进入或者离开之前或之后都必须要走这个地方!

    在路由跳转之前或者跳转之后自动执行相应的钩子函数 ;ps:钩子函数在相应的时间段会自动执行,不用调用

    全局前置守卫beforeEach

    // 全局前置守卫函数! 【作用:标题设置、权限判断如登录验证等等!】 // 路由实例对象.beforeEach((去到的路由,来自的路由,next函数)=>{}) router.beforeEach((to, from, next) => { // 一定要next!否则路由就无法继续! // console.log(to) // 去的路由地址信息 // console.log(from) // 来的路由地址信息 console.log("【全局】所有路由进入之前都会执行!") // 设置标题 document.title = to.meta.tit; // 登录判断 if (to.meta.needLogin) { // 是否需要判断登录 if (localStorage.getItem("studentInfo")) { // 登录了 next(); } else { // 没登录 router.push('/login') } } else { // 不需要登录 next(); } }) 全局解析守卫beforeResolve router.beforeResolve((to, from, next) => { //全局解析守卫,2.5.0新增,这和router.beforeEach类似,区别是再导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用 console.log("全局"); console.log("beforeResolve", to, from); next() }) 全局后置守卫afterEach // 全局后置守卫! router.afterEach((to,from)=>{ // console.log(to) // console.log(from) console.log("【全局】所有路由离开之后都会执行!"); }) 路由独享守卫beforeEnter(写在路由配置里面) const router = new Router({ mode: 'history', base: process.env.BASE_URL, routes: [{ path: "/", redirect: "/a" }, { path: "/a/:id", //路由独享的守卫 beforeEnter: (to, from, next) => { console.log("路由独享") console.log('before enter'); next() }, component: () => import('@/components/HelloWorld'), }, { path: "/b", alias: '/world',//别名,URL中'/b' 和 '/world'效果一样; component: () => import('@/components/BBB'), }] })

    局部导航守卫

    beforeRouteEnter // 局部导航守卫! // 局部路由进入之前 beforeRouteEnter(to,from,next){ console.log("局部路由进入之前") // console.log(this) // 不能再这里使用this!这个时候组件还没有创建! next(); }, beforeRouteUpdate // 局部路由更新前 beforeRouteUpdate(to,from,next){ console.log("局部路由更新前") next(); }, beforeRouteLeave // 局部路由离开前 beforeRouteLeave(to,from,next){ console.log("局部路由离开前") // 保存判断! // if(window.confirm('是否保存')){ // next(); // } next(); }

    vue-router 同路由跳转,页面组件不会被再次创建!所以如果详情跳转到详情页面,下一次created不会执行!所以不能简单的在created里面请求数据,还需要监听$route的变化

    beforeRouteUpdate监听路由地址变化! // 局部路由更新前 beforeRouteUpdate(to,from,next){ console.log("局部路由更新前") console.log(this.$route.params.id) // 获取路由的动态数据,提交给接口去请求数据! next(); } 使用watch监听路由变化 watch:{ $route:{ deep:true, handler(){ console.log(this.$route.params.id); } } }
    Processed: 0.008, SQL: 9