【问题标题】:Cannot access object properties from dynamic import. Vue.js + ts无法从动态导入访问对象属性。 Vue.js + ts
【发布时间】:2020-11-08 11:53:03
【问题描述】:

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

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 在加载对象之前尝试使用该值时会出现这种错误。所以,我尝试添加额外的加载变量,但没有发生任何事情。有什么办法可以解决吗?

【问题讨论】:

    标签: javascript typescript vue.js vue-component dynamic-import


    【解决方案1】:

    由于import 是一个异步函数,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;
      }
    

    【讨论】:

    • 这正是我想要的。在修改我的代码以承诺后按预期工作,谢谢!没有足够的评分来显示我的支持,但它已被评分。
    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 2017-05-16
    • 2011-08-10
    • 1970-01-01
    • 2021-11-06
    • 2014-03-10
    • 2018-03-02
    • 2013-07-21
    相关资源
    最近更新 更多