gpt4 book ai didi

javascript - 如何访问 vue-router 中的异步存储数据以便在 beforeEnter Hook 中使用?

转载 作者:可可西里 更新时间:2023-11-01 01:58:37 26 4
gpt4 key购买 nike

如何访问通过存储操作异步检索的 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 Hook 需要根据数据库中的真实数据而不是默认数据做出决定)

最佳答案

您可以通过从 vuex 操作返回一个 promise 来做到这一点,正如所解释的那样 here并从 beforeEnter 本身内部调用调度。

代码应该如下所示:

import store from './vuex/store';


// following is an excerpt of the routes object:
{
path: '/example',
component: Example,
beforeEnter: (to, from, next) =>
{
store.dispatch('initApp').then(response => {
// the above state is not available here, since it
// it is resolved asynchronously in the store action
}, error => {
// handle error here
})
}
}

关于javascript - 如何访问 vue-router 中的异步存储数据以便在 beforeEnter Hook 中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42579601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com