当前位置: 首页 > news >正文

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 StringFieldcase "number":return NumberFieldcase "array":return ArrayFieldcase "object":return ObjectFieldcase "integer":return NumberFielddefault:console.warn(`${type.value} is not supported`)}
})
</script>

http://www.lryc.cn/news/375851.html

相关文章:

  • 嵌入式中间件_2.嵌入式中间件的分类
  • 论文精读——KAN
  • 全国产城市轨道交通运营公安AI高清视频监控系统
  • python连接mysql数据库、FastAPI、mysql-connector-python
  • 【idea】解决springboot项目中遇到的问题
  • ubuntu22.04禁止自动休眠的几种方式
  • 智能网站管理系统
  • Android Service学习笔记
  • amr文件怎么转换成mp3?超好用的四种转换方法介绍!
  • 翻转数位00
  • 工具:安装R语言的R包的各种方法
  • 注意力机制和Transformer模型各部分功能解释
  • 短路是怎么形成的
  • 【ZZULIOJ】1106: 回文数(函数专题)
  • 数据库设计规范总结
  • 深度学习(九)——神经网络:最大池化的作用
  • 「前端+鸿蒙」鸿蒙应用开发-ArkTS语法说明-组件声明
  • python的subprocess 模块
  • 【Arc gis】使用DEM提取流域范围
  • 大模型技术工程师:抓住时代机遇,成为行业精英_
  • 孟德尔随机化R包:TwoSampleMR和MR-PRESSO安装
  • 6月18日 Qtday4
  • Vue3模拟国足18强赛抽签
  • mesa编译器nir信息储存问题
  • windows下mysql设置开机自启动
  • L2-002 链表去重(C++)
  • 异或运算在面试题中的应用
  • 【2024最新华为OD-C/D卷试题汇总】[支持在线评测] 单词大师(100分) - 三语言AC题解(Python/Java/Cpp)
  • LabVIEW在SpaceX的应用
  • 【Android面试八股文】讲一讲String、StringBuffer和StringBuilder在进行字符串操作时候的效率