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>

相关推荐

  1. Vue3使用component动态展示组件

    2024-06-19 09:54:03       39 阅读
  2. Vue3使用动态组件

    2024-06-19 09:54:03       69 阅读
  3. vuecomponents动态添加组件

    2024-06-19 09:54:03       52 阅读
  4. Vue动态组件component>传递变量

    2024-06-19 09:54:03       54 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-19 09:54:03       110 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-19 09:54:03       119 阅读
  3. 在Django里面运行非项目文件

    2024-06-19 09:54:03       98 阅读
  4. Python语言-面向对象

    2024-06-19 09:54:03       106 阅读

热门阅读

  1. 前端面试题——网络篇

    2024-06-19 09:54:03       46 阅读
  2. 数据传输安全(为支付宝第三方做铺垫)

    2024-06-19 09:54:03       41 阅读
  3. HTML(6)——表单

    2024-06-19 09:54:03       38 阅读
  4. 【数据结构】练习集

    2024-06-19 09:54:03       31 阅读
  5. template标签

    2024-06-19 09:54:03       41 阅读
  6. Springboot应用设置跳过SSL证书认证

    2024-06-19 09:54:03       52 阅读
  7. MySQL-DML-约束

    2024-06-19 09:54:03       42 阅读
  8. 研导AI写作:辅助创作的未来伙伴

    2024-06-19 09:54:03       38 阅读
  9. vue3基础

    2024-06-19 09:54:03       42 阅读