我的客户希望拥有具有其他内容的应用程序的其他实例(所谓的“主题”)。我们决定使用环境变量+预填充对象的内容。所以,这个内容可能存在,也可能不存在。 我创建了一个函数,有条件地导入包含所有内容的模块,它实际上甚至可以工作:
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
。我建议您使用 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;
}
关于javascript - 无法通过动态导入访问对象属性。 Vue.js + ts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62974897/