Vue2 实现动态组件
// template
<component :is="currentTabComponent" />
// JSX
<component is={this.currentTabComponent} />
实际上,上述 JSX 是不生效的。
解决方案
- 方法一
const tabData = [
{ key: 'weightList', name: '司磅', componentName: 'weight' },
{ key: 'qualityList', name: '质检', componentName: 'quality' },
]
computed: {
component () {
const Tag = tabData.find(item => item.key === this.data)?.componentName
return Tag ? <Tag></Tag> : null
}
},
render () {
return <a-card class="m-b-20">
{this.component}
</a-card>
}
- 方法二
computed: {
componentName () {
return tabData.find(item => item.key === this.data)?.componentName
},
},
render (h) {
return <a-card class="m-b-20">
{h(this.componentName)}
</a-card>
}
使用场景
tab 切换,渲染对应的组件。
render () {
const tab = <a-tabs v-model={this.data}>
{tabData.map(item => {
return showTab(this.actions, item.key) && <a-tab-pane key={item.key} tab={item.name} />
})}
</a-tabs>
return <a-card class="m-b-20">{tab}</a-card>
}
Vue3 实现动态组件
// 子组件
import { defineComponent } from 'vue'
export default defineComponent({
setup () {
return () => (
<div>子组件1</div>
)
}
})
// 应用动态组件
import { defineComponent, h, resolveComponent, defineAsyncComponent, ref } from 'vue'
export default defineComponent({
components: {
comp1: defineAsyncComponent(() => import('./components/comp1')),
...
},
setup () {
let tabComponent = ref('comp1');
return () => (
<>
<button onClick={() => tabComponent.value = 'comp1'}>comp1</button>
{h(resolveComponent(tabComponent.value))}
</>
)
}
})
- 使用 defineAsyncComponent 动态载入组件
- 使用 resolveComponent 请求组件
- 使用 h 渲染函数加载组件