解决办法很简单.将init
或等效Vuex action
添加到store 的相关部分
init ({ dispatch }) { // Could also be async and use await instead of return
return Promise.all([
dispatch('getUserSession'), // Using another action
dispatch('auth/init'), // In another module
fetch('tehKittenz') // With the native fetch API
// ...
])
}
上面的代码可以使用任何返回Promise
的代码.
然后用beforeEach
在路由上创建一个global navigation guard
// In your router initialization code
const storeInit = store.dispatch('init')
// Before all other beforeEach
router.beforeEach((to, from, next) => {
storeInit.then(next)
.catch(e => {
// Handle error
})
})
这样,如果在存储完全加载之前进行路由,路由只需等待
不要忘记使用conditional rendering之类的东西,以免在路由等待数据时显示空白屏幕.
*:这将阻止所有路由和导航,只要数据正在获取.小心.