无法从动态导入访问对象属性。 Vue.js + ts

Cannot access object properties from dynamic import. Vue.js + ts

我的客户希望应用程序的其他实例也包含其他内容(所谓的 'themes')。我们决定使用 env 变量 + 带有内容的预填充对象。因此,此内容可能存在,也可能不存在。 我创建了一个有条件地导入包含所有内容的模块的函数,它甚至可以正常工作:

theme: string;
hasAnyTheme: boolean;

static getThemedMiscContent(): {[key: string]: string} {
    let miscContent = {};
      if (hasAnyTheme) {
          import(`@/themes/customers-themes/${theme}/ThemedContent`)
            .then(themedContent => {
              miscContent = Object.assign(miscContent, themedContent.ThemedMiscContent);
            });
    }
    return miscContent;
  }

但是当我从组件调用它时,我实际上无法读取对象的属性,而我可以读取对象本身。

// computed
miscThemedContent(): {[key: string]: string} {
  return ThemeUtil.getThemedMiscContent();
}

// template
{{ miscThemedContent }} // is totally fine
{{ miscThemedContent.someValue }} // undefined

奇怪的是,这个问题只出现在我使用该功能的 3 个组件中的一个中。其他人工作得很好。 据我所知,当 Vue 在加载对象之前尝试使用该值时,就会出现这种错误。因此,我尝试添加额外的加载变量,但没有任何反应。有什么办法可以解决这个问题吗?

因为 import 是一个异步函数,所以 miscContent 可以在导入函数执行完成之前返回。我建议你在返回 miscContent 之前使用 async/await 语法等待实际结果,它应该是这样的:

static async getThemedMiscContent(): {[key: string]: string} {
    let miscContent = {};
      if (hasAnyTheme) {
          const importTheme = await import(`@/themes/customers-themes/${theme}/ThemedContent`);
          if (importTheme && importTheme.ThemedMiscContent) {
              miscContent = Object.assign(miscContent, importTheme.ThemedMiscContent);
          }
    }
    return miscContent;
  }