如何解决访问router.js中的Vuex存储时出现异步等待问题 纯.then语法 async/await语法和.then语法的混合
我正在尝试访问路由器文件中的Vuex存储。 我需要根据商店的data.length定义路线。 例如,如果store.data为空,则只需要公司列表路由。 如果没有,我只需要登录即可。 实际上数据不是空数组,但它总是记录为空数组,如何在没有此问题的情况下获取存储的数据(异步/等待)? 这是我的代码。
import Vue from 'vue';
import Router from 'vue-router';
import store from '@/store';
Vue.use(Router);
let data = [];
async function getData() {
data = await store.dispatch('auth/fetchCompanyList');
}
getData();
console.log('data',data);
//data is always empty array.
let routes = [];
if (data.length === 0) {
routes = [
{
path: '/company-list',name: 'CompanyList',component: () => import('../pages/admin/company/List.vue'),},];
} else {
routes = [
{
path: '/signin',name: 'Signin',component: () => import('../pages/signin.vue'),];
}
console.log('Route: ',routes);
const router = new Router({
mode: 'history',base: process.env.BASE_URL,// base: process.env.BASE_URL + '/ui/',routes,});
export default router;
解决方法
在记录数据时,该数据将为空,因为它尚未从store方法收到答案。您可以使用$(GTEST_DIR)
来访问Promise的值。然后,您可以使用addRoutes()
功能随意添加更多路由到路由器。
实现可以如下所示:
.then()
,
问题在于getData
方法是异步的(它将返回一个Promise),而您不必等待该Promise的结果(它正在等待处理)。如果没有.then
块或await
关键字,则承诺将无法解决(它将处于待处理状态)。
结果,handleData
将以data
的初始值运行,该初始值是一个空数组([])。
在整个问题中使用async/await
语法将是具有挑战性的,因为await
仅可用于包含async
关键字的函数范围。
因此,我将展示如何使用.then
和async/await
的混合以及如何仅使用.then
语法。
出于一致性考虑,我个人不喜欢将.then
和async/await
混合使用,因为它们做同样的事情。但是,我将由您决定采用哪种方法。
纯.then
语法
import Vue from 'vue';
import Router from 'vue-router';
import store from '@/store';
Vue.use(Router);
let data = [];
function getData() {
return store.dispatch('auth/fetchCompanyList');
}
getData().then((resolvedData) => {
data = resolvedData
let routes = [];
if (data.length === 0) {
...
} else {
...
}
});
const router = new Router({
...
});
export default router;
async/await
语法和.then
语法的混合
import Vue from 'vue';
import Router from 'vue-router';
import store from '@/store';
Vue.use(Router);
let data = [];
async function getData() {
let resolvedPromise = await store.dispatch('auth/fetchCompanyList');
return resolvedPromise;
}
getData().then((resolvedData) => { // the .then returns the resolved promise. I cannot use `async/await` here because the getData method that is called is not within a scope with the async keyword
data = resolvedData
// this will resolve into a promise (any method with the 'async' keyword will resolve into a promise(either rejected or resolved))
let routes = [];
if (data.length === 0) {
...
} else {
...
}
});
const router = new Router({
...
});
export default router;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。