Vue3使用component动态展示组件

前言:

最近在研究gitHub中的一个项目并将与自己之前完成的项目进行结合,其中有一个功能就是需要使用根据不同的字段,渲染不同的组件,查阅资料发现可以使用component完成这个功能,在实现的过程中也会遇见一些坑,总结如下,与君共勉。

官网:

组件基础 | Vue.js
有些场景会需要在两个组件间来回切换,比如 Tab 界面:需要通过 Vue 的 <component> 元素和特殊的 is attributel来实现:

<component :is="tabs[currentTab]"></component>

在上面的例子中,被传给 :is 的值可以是以下几种:

  • 被注册的组件名
  • 导入的组件对象

在两个组件之间进行切换: 

注意:is如果使用字符串会加载不出来传递给is的值应该为组件名


<template>
  <Child1 />
  <Child2 />
  <component :is="flag ? StringField : NumberField"></component>
  <el-button @click="flag = !flag">切换组件</el-button>
</template>
<script setup>
  import { ref } from 'vue'
  import StringField from './Child1.vue'
  import NumberField from './Child2.vue'
  const flag = ref(true)
 </script>

如果在多个组件之间进行选择:

注意:在选取type的时候需要使用computed

<template>
  <component class="schema-item" :is="getComponentFlag" :schema="props.schema"></component>
</template>

<script lang="ts" setup>
import { defineProps, computed,ref} from "vue"
import StringField from "../../../lib/fields/StringField.vue"
import NumberField from "../../../lib/fields/NumberField.vue"
import ArrayField from "../../../lib/fields/ArrayField.vue"
import ObjectField from "../../../lib/fields/ObjectField.vue"
const type = ref("string")
// 根据 type 动态设置组件 需要使用计算属性
const getComponentFlag = computed(() => {
  switch (type.value) {
    case "string":
      return StringField
    case "number":
      return NumberField
    case "array":
      return ArrayField
    case "object":
      return ObjectField
    case "integer":
      return NumberField
    default:
      console.warn(`${type.value} is not supported`)
  }
})
</script>

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值