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

Javascript 无法从动态导入访问对象属性。Vue.js+;ts,javascript,typescript,vue.js,vue-component,dynamic-import,Javascript,Typescript,Vue.js,Vue Component,Dynamic Import,我的客户希望该应用程序的其他实例也包含其他内容(所谓的“主题”)。我们决定使用env variable+带内容的预填充对象。因此,该内容可能存在,也可能不存在。 我创建了一个函数,可以有条件地导入包含所有内容的模块,它甚至可以正常工作: theme: string; hasAnyTheme: boolean; static getThemedMiscContent(): {[key: string]: string} { let miscContent = {}; if (

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

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尝试使用该值时,就会出现这种错误。所以,我尝试添加额外的加载变量,但什么也没有发生。有没有办法解决这个问题?

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

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;
  }

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

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;
  }

这正是我想要的。在将我的代码修改为承诺后按预期工作,谢谢!没有足够的评分来显示我的支持率,但它是得分的。这正是我想要的。在将我的代码修改为承诺后按预期工作,谢谢!没有足够的评分来显示我的得票率,但已经得分了。