前言:
最近在研究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>