导航守卫的理解和使用

时间:2019-10-22 18:25:28   收藏:0   阅读:122

1、导航守卫钩子

导航守卫的用途主要是在用户离开页面前提醒用户,和页面访问前先登录。共有7个钩子,其中全局钩子有3个,组件钩子有3个,路由管道钩子有1个。

全局钩子:

const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
    // ...(2)
    //全局前置守卫
})
router.beforeResolve((to, from, next) => {
   // ...(6)
    //全局解析守卫

})
router.afterEach((to, from) => {
  // ...(7)
  //全局后置守卫
}

组件内的钩子:

export default {
  data(){},
  beforeRouteEnter (to, from, next) {
    //....(5)
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) {
    // ... (3)
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // ... (1)
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }
}

路由管道钩子:

const router = new VueRouter({
  routes: [
    {
      path: ‘/foo‘,
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...(4)
      }
    }
  ]
})

2、参数解析

每个守卫方法接收三个参数:

确保要调用 next 方法,否则钩子就不会被 resolved。

3、导航流程

  1. 导航被触发。
  2. 在失活的组件里调用离开守卫。
  3. 调用全局的 beforeEach 守卫。
  4. 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
  5. 在路由配置里调用 beforeEnter
  6. 解析异步路由组件。
  7. 在被激活的组件里调用 beforeRouteEnter
  8. 调用全局的 beforeResolve 守卫 (2.5+)。
  9. 导航被确认。
  10. 调用全局的 afterEach 钩子。
  11. 触发 DOM 更新。
  12. 用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。

4、导航流程图(页面切换的执行顺序)

技术分享图片

5、页面跳转前需登录  - 实验

 1)首先需要给isLogin为false,表示未登录,将该值初始在store内,

export default new Vuex.Store({
  state: {
    isLogin: false,
  },
  mutations: {
    handleLogin(state, login) {
      state.isLogin = login;
    },
  },
});

 

 2)在登录页- 登录按钮 设置点击时修改store内的isLogin为true,同时跳转到首页‘/home’

methods: {
    ...mapMutations([‘handleLogin‘]),
    handleSubmit() {
      // 修改store里的isLogin为true,表示登录了 
      this.handleLogin(true)
      this.$router.push({path: ‘/home‘})
    }
  }

 

 3)每一次页面切换时,全局钩子beforeEach都会触发,在该钩子内判断 是否登录了?若没有登录,需要跳转到 登录页 ‘/login’,否则 可以跳转 

router.beforeEach((to, from, next) => {
  const isLogin = obj.state.isLogin;
  if (to.path === ‘/login‘ || isLogin) {
    next();
  } else {
    next(‘/login‘);
  }
});

 6、参考文献

https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E5%AE%88%E5%8D%AB

https://www.cnblogs.com/minigrasshopper/p/7928311.html

 

route

原文:https://www.cnblogs.com/Ladai/p/11721177.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!