访问router.js中的Vuex存储时出现异步等待问题

时间:2020-08-25 08:52:59

标签: vue.js async-await vuex

我正在尝试访问路由器文件中的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;

2 个答案:

答案 0 :(得分:0)

在记录数据时,该数据将为空,因为它尚未从store方法收到答案。您可以使用$(GTEST_DIR)来访问Promise的值。然后,您可以使用addRoutes()功能随意添加更多路由到路由器。

实现可以如下所示:

.then()

答案 1 :(得分:0)

问题在于getData方法是异步的(它将返回一个Promise),而您不必等待该Promise的结果(它正在等待处理)。如果没有.then块或await关键字,则承诺将无法解决(它将处于待处理状态)。

结果,handleData将以data的初始值运行,该初始值是一个空数组([])。

在整个问题中使用async/await语法将是具有挑战性的,因为await仅可用于包含async关键字的函数范围。

因此,我将展示如何使用.thenasync/await的混合以及如何仅使用.then语法。

出于一致性考虑,我个人不喜欢将.thenasync/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;