我想显示一个组件取决于它的类型。让我解释一下。
我有多个彼此相似的组件,但取决于给定的类型,它们应该显示一些不同的内容。使用defineAsyncComponent方法,我可以导入组件并轻松使用它们。示例:
const CheckboxControl = defineAsyncComponent(
() => import('@/components/editor/controls/CheckboxControl.vue'),
);这很好,但如果我这样做,我有大量的进口组件。我不想要这个。我的方法是将defineAsyncComponent封装在箭头函数中,如下所示:
const loadComponent = async (type: string) =>
defineAsyncComponent(
() =>
import(
`@/components/editor/controls/${type[0].toUpperCase()}${type.substring(
1,
)}Control.vue`
),
);在模板中,我可以像下面的<component :is="renderComponent(control.type)" />那样呈现组件
但这给了我以下警告:
[Vue warn]: Component is missing template or render function.等待defineAsyncComponent方法不能解决这个问题。
我做错了什么?如何动态导入这些组件?
更新
以下是control.type属性中的所有可能性:
更新2
这是我当前正在运行的代码:
const CheckboxControl = defineAsyncComponent(
() => import('@/components/editor/controls/CheckboxControl.vue'),
);
const DateControl = defineAsyncComponent(
() => import('@/components/editor/controls/DateControl.vue'),
);
const EmailControl = defineAsyncComponent(
() => import('@/components/editor/controls/EmailControl.vue'),
);
const NumberControl = defineAsyncComponent(
() => import('@/components/editor/controls/NumberControl.vue'),
);
const RadioControl = defineAsyncComponent(
() => import('@/components/editor/controls/RadioControl.vue'),
);
const RangeControl = defineAsyncComponent(
() => import('@/components/editor/controls/RangeControl.vue'),
);
const SelectControl = defineAsyncComponent(
() => import('@/components/editor/controls/SelectControl.vue'),
);
const TextareaControl = defineAsyncComponent(
() => import('@/components/editor/controls/TextareaControl.vue'),
);
const TextControl = defineAsyncComponent(
() => import('@/components/editor/controls/TextControl.vue'),
);
const loadComponent = (type: string) => {
switch (type) {
case 'checkbox':
return CheckboxControl;
case 'date':
return DateControl;
case 'email':
return EmailControl;
case 'number':
return NumberControl;
case 'radio':
return RadioControl;
case 'range':
return RangeControl;
case 'select':
return SelectControl;
case 'textarea':
return TextareaControl;
case 'text':
return TextControl;
default:
// TODO: show error component if type not supported
break;
}
};更新3
对于当前的设置,我使用vite作为构建工具。我使用的vite版本是2.9.5。我使用的vue版本是3.2.33,类型记录版本是4.6.3。
发布于 2022-07-14 09:03:19
谢谢@Estus酒瓶,谢谢您的帮助:)
所以问题是我试图用@别名导入它。我改变了我的方法:
const loadComponent = (type: string) =>
defineAsyncComponent(
() =>
import(
`./controls/${type[0].toUpperCase()}${type.substring(1)}Control.vue`
),
);现在起作用了。
我不知道为什么在这种情况下它不使用@别名,因为当我使用它时
const CheckboxControl = defineAsyncComponent(
() => import('@/components/editor/controls/CheckboxControl.vue'),
);也许有人能解释这件事?
发布于 2022-07-14 08:28:03
async强制函数返回允诺对象,而组件则是预期的。它应该是正常的职能:
const loadComponent = (type: string) => ...是defineAsyncComponent处理来自import的底层承诺。
https://stackoverflow.com/questions/72977357
复制相似问题