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
