路由的全局前置守卫


 1 router.beforeEach((to, from, next) => {
 2   // 获取仓库里的登录信息
 3   const auth = router.app.$options.store.state.auth
 4 
 5   if (auth && to.path.indexOf('/auth/') !== -1) {
 6     // 如果当前用户已登录,且目标路由包含 /auth/ ,就跳转到首页
 7     next('/')
 8   } else {
 9     next()
10   }
11 })
  • 使用 router.beforeEach 注册一个全局前置守卫,它在导航被触发后调用,我们可以通过跳转或取消的方式守卫导航,参数我们上面介绍过;
  • 使用 router.app 可以获取 router 对应的 Vue 根实例,使用实例的 $options.store 可以从选项中访问仓库;
  • 使用 next('/') 或者 next({ path: '/' }) 来跳转到一个新的地址;
  • 实例的 $options 是用于当前 Vue 实例的初始化选项:
  • new Vue({
      el: '#app',
      router,
      store,
      components: { App },
      template: '<App/>',
      created() {
        console.log(this.$options.el) // => '#app'
      }
    })

    在路由配置文件中,我们还可以通过下面的方式访问仓库:

  • import store from '../store'
    const auth = store.state.auth

     


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM