【发布时间】:2019-09-29 07:07:30
【问题描述】:
看看这个:
import accountModule from '@/store/modules/account/account';
import otherModule from '@/store/modules/other/other';
export default new Vuex.Store({
modules: {
account: accountModule,
other: otherModule,
}
});
other 中的数据初始化依赖于account 模块,因为account 模块具有用户特定的设置。假设other.state.list 依赖于account.state.settings.listOrder。但是,我希望account 模块的数据来自服务器。这是异步的。因此,当other 尝试设置时,它不能只尝试引用account.state.settings.listOrder,因为服务器的响应可能还没有回来。
我尝试在accountModule 中导出一个promise,它可以通过模块本身解决。但这种方法似乎行不通。
import accountModulePromise from '@/store/modules/account/account';
accountModulePromise.then(function (accountMoudle) {
import otherModule from '@/store/modules/other/other';
...
});
这给了我一个错误,说 import 语句需要是顶级的。
以下也不起作用:
let accountModule = await import '@/store/modules/account/account';
import otherModule from '@/store/modules/other/other';
...
它给了我一个错误,说await 是一个保留字。不过我很困惑,因为https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import 说我应该能够做到。
【问题讨论】:
-
仍然,为什么要延迟 vuex 模块 的导入。或者你想在
otherModule等accountModule上进行操作? -
@Frank 最后,我希望
otherModule中的数据设置等待accountModule。但为了做到这一点,我认为我需要延迟accountModule的导入,因为我希望第二行代码仅在第一行完成从服务器获取其内容并进行设置时执行。 -
好像 other 依赖于 account,那么 otherModule 应该导入 accountModule。试图在商店里解决似乎是错误的。究竟是什么依赖?
-
@eric99 在
other是account的子模块的意义上?如果是这样,那不是我想要的结构方式。如果没有,还有一个问题是我将account附加到我的 Vuex 商店的位置。如果我开始在多个地方导入它,它会因大量不必要的网络请求而减慢速度。在我的真实应用程序中还有一个更复杂的问题(我在这个问题中忽略了以保持简单),有许多模块依赖于account。 -
如果你使用标准的 Vue CLI 设置,导入不是运行时指令——而是 webpack 使用然后捆绑代码。因此,await 不能与它一起使用,并且您不能分配它的结果(它不是函数调用),并且多个引用不会“减慢速度”。您应该将导入视为编译时声明而不是运行时指令。
标签: javascript asynchronous vue.js vuex