JSX 实现动态组件

Vue2 实现动态组件

// template
<component :is="currentTabComponent"  />

// JSX
<component is={this.currentTabComponent} />

实际上,上述 JSX 是不生效的。

解决方案

  1. 方法一
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>
}
  1. 方法二
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))}
      </>
    )
  }
})
  1. 使用 defineAsyncComponent 动态载入组件
  2. 使用 resolveComponent 请求组件
  3. 使用 h 渲染函数加载组件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值