我有很多组件,我想按需导入。我有一个下拉列表,其中实际上包含组件列表,这是什么加载。我尝试了这个例子
<component :is="componentLoader"></component>
在脚本中
componentLoader () {
return () => import('@/components/testDynamic')
}
- testDynamic**是一个组件名(目前我尝试使用静态组件)。
获取此错误
GET http://localhost:8080/0.js net::ERR_ABORTED 404
[Vue warn]: Failed to resolve async component: function () {
return __webpack_require__.e/* import() */(0).then(__webpack_require__.bind(null, "./src/components/testDynamic.vue"));
}
Reason: Error: Loading chunk 0 failed.
如何解决这个问题?我做错了什么吗?或者有没有其他方法来动态导入组件?
6条答案
按热度按时间8i9zcol21#
可以在单个文件组件中本地注册异步动态组件,如下所示:
在您的模板中:
如果注册多个组件,则只需将
current
的值更改为所需的组件。对于许多组件,可以导入一个对象,将组件名称Map到其各自的文件路径,然后按如下方式注册它们:
其中
myComponents
导出为:bq8i3lrv2#
我遇到了同样的问题,因为我使用的是Vue 3,这里给出的解决方案对我都不起作用。经过一番研究,我发现定义动态组件(异步组件)的过程在Vue 3中略有不同。我希望这段代码能对大家有所帮助。
o4hqfura3#
我经常使用下面的方法(Vue 2),效果很好。
下面的简单示例允许动态指定要加载的组件:- 因为调用launchEditForm只需要一个字符串作为参数,如果你可以将文件名表示为字符串,那么你就可以加载它。
保持launchEditForm为“计算”属性非常重要,即不要在“方法”中定义它。
如果您调用的文件不存在,则会出现如下所示的运行时错误:找不到模块“./components/cliente/forms/不存在.vue”
请注意,在上面的示例中,该文件位于.../src/components/clients/forms/EditContactsForm.vue
通常这种类型的动态导入是在模态中完成的,它只是在模态中移动标签的一种情况。显然我们可以使用带有布尔变量的v-if来打开和关闭模态。但是上面的代码应该说明核心点-即组件名称可以动态生成,组件可以动态加载。
55ooxyrt4#
对我起作用的是等待componentLoader函数,因为import函数返回一个承诺!
qnakjoqk5#
对于VUE 3合成API,在更新lifecycle之前使用defineasynccomponent和一个挂接
示例将组件作为 prop 传递
如果你不想在控制台上的消息抱怨你可以跟随errorhandler
dpiehjr46#
下面是Brian Lee对答案的扩展,包括额外的UX覆盖范围和Webpack优化:
这里,
v-if
可以是取决于assetToEdit
的成功加载的某个布尔参数。