Vue.js 在Vuejs中动态注册子组件
我有一个组件,我们称它为Vue.js 在Vuejs中动态注册子组件,vue.js,vuejs2,Vue.js,Vuejs2,我有一个组件,我们称它为Parent.vue(代码如下所示)。它使用Vuejs提供的标记动态呈现组件 它使用一个名为child的道具,该道具描述了子组件的类型及其将使用的道具 现在的问题是,即使我的Parent.vue一次只渲染一个子组件,它也必须使用components对象注册所有3个组件 所以,我的问题是:有没有一种方法可以根据子组件的类型动态导入和注册这些子组件?类似于一个函数,它检查child.type字段,并仅使用所需的子对象创建组件对象 任何帮助都将不胜感激 <template
Parent.vue
(代码如下所示)。它使用Vuejs提供的
标记动态呈现组件
它使用一个名为child
的道具,该道具描述了子组件的类型及其将使用的道具
现在的问题是,即使我的Parent.vue
一次只渲染一个子组件,它也必须使用components
对象注册所有3个组件
所以,我的问题是:有没有一种方法可以根据子组件的类型动态导入和注册这些子组件?类似于一个函数,它检查child.type
字段,并仅使用所需的子对象创建组件
对象
任何帮助都将不胜感激
<template>
<div>
<component
:is="getComponentName(child.type)"
v-bind="child.props"
>
</component>
</div>
</template>
<script>
import Button from './Button.vue'
import InputText from './InputText.vue'
import DataTable from './DataTable.vue'
export default{
props:{
child: Object
},
components:{
Button,
InputText,
DataTable
},
methods:{
getComponentName(type){
switch(type){
case 'button': return 'Button'
case 'input-text': return 'InputText'
case 'table': return DataTable
}
}
}
}
</script>
从“./Button.vue”导入按钮
从“./InputText.vue”导入InputText
从“./DataTable.vue”导入DataTable
导出默认值{
道具:{
子对象:对象
},
组成部分:{
按钮
输入文本,
数据表
},
方法:{
getComponentName(类型){
开关(类型){
案例“按钮”:返回“按钮”
案例“输入文本”:返回“输入文本”
案例“表”:返回数据表
}
}
}
}
我在这些方面使用了一种方法,它很有效
<template>
<div>
<component
:is="getComponentName(child.type)"
v-bind="child.props"
>
</component>
</div>
</template>
<script>
export default{
props:{
child: Object
},
methods:{
getComponentName(type){
switch(type){
case 'button': return require('./components/Button.vue')
case 'input-text': return require('./components/InputText.vue')
case 'table': return require('./components/Table.vue')
}
}
}
}
</script>
导出默认值{
道具:{
子对象:对象
},
方法:{
getComponentName(类型){
开关(类型){
案例“button”:返回要求(“./components/button.vue”)
案例“输入文本”:返回要求(“./components/InputText.vue”)
案例“table”:返回要求(“./components/table.vue”)
}
}
}
}
由于是组件的
属性
组件可以接受组件定义
(请参阅更多信息)。因此,您可以将其设置为返回动态导入函数的factory函数
<template>
<div>
<button @click='name = "Apple"'>Apple</button>
<button @click='name = "Banana"'>Banana</button>
<component :is='component'/>
</div>
</template>
<script>
export default {
data: () => ({
name: 'Apple'
}),
computed: {
component () {
let name = this.name
return () => import(`@/components/${name}`)
}
}
}
</script>
苹果
香蕉
导出默认值{
数据:()=>({
名称:“苹果”
}),
计算:{
组件(){
让name=this.name
return()=>import(`@/components/${name}`)
}
}
}
通过这种方式,当您在不使用显式寄存器的情况下使用组件时,您的组件将被加载并执行。Hi,这个示例是否有助于您完成所需的工作?它展示了如何在组件之间动态切换。谢谢@Andrew1325。你能告诉我为什么这不起作用吗:
case'button':return()=>import(“./my async component./components/button.vue”)
为什么我必须只使用require
是的,我不太清楚为什么。这样做是一种动态导入,我认为需要一个babel插件才能正确传输。我在这里尝试了你的解决方案:它给了我一个错误。请在你的机器上尝试。我仍然不知道为什么。我只能接受一个答案,但是,官方Vuejs文档中记录了这种方法,因此这也是正确的答案。实际上,使用require(…)
和import(…)
之间有很大区别。如果您使用require(…)
,则Webpack不会分割您的区块,这意味着您将加载所有已使用或未使用的组件。如果您仍然想使用require
,您可以使用require
的特殊语法告诉Webpack按()=>新承诺拆分此文件(resolve=>{require(['./components/Hello.vue'],resolve)
。请参阅。供将来参考:let name=this。name
很重要,否则计算属性将失去反应性。