如何访问通过存储操作异步检索的 beforeEnter 中的存储数据?
import store from './vuex/store';
store.dispatch('initApp'); // in here, async data will be fetched and assigned to the store's state
// following is an excerpt of the routes object:
{
path: '/example',
component: Example,
beforeEnter: (to, from, next) =>
{
if (store.state.asyncData) {
// the above state is not available here, since it
// it is resolved asynchronously in the store action
}
}
}
这在第一个页面加载或页面重新加载后尤其重要,此时正在获取初始数据并且路由器需要等待该数据以允许用户访问该页面或不允许。
路由器是否可以“等待”获取数据?或者结合异步 vuex 存储数据处理导航守卫的最佳方式是什么?
(哦,预填充“asyncData”不是解决方案,因为 beforeEnter 挂钩需要根据数据库中的真实数据而不是默认数据做出决定)
原文由 santacruz 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以通过从 vuex 操作返回一个承诺来做到这一点,正如 此处 所解释的那样,并从
beforeEnter
本身内部调用调度。代码应如下所示: