路由的全局前置守衛


 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