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

vue3使用动态component

使用场景:

多个组件通过component标签挂载在同一个组件中,通过触发时间进行动态切换。vue3与vue2用法不一样,这里有坑!

使用方法:

1.通过vue的defineAsyncComponent实现挂载组件

2.component中的is属性

父组件:

<template>
  <div>
    <div v-for="item in person.data" :key="item" @click="btn(item)">
      {{ item.name }}
    </div>
    <h1>下面为动态组件</h1>
    <component :is="person.componen"> </component>
  </div>
</template>

<script setup>
import { reactive, onMounted, defineAsyncComponent } from "vue";
const One = defineAsyncComponent(() => import("./One.vue"));
const Two = defineAsyncComponent(() => import("./Two.vue"));

const person = reactive({
  componen: "",
  data: [
    { type: "one", name: "显示组件一" },
    { type: "two", name: "显示组件二" },
  ],
});
function btn(item) {
  if (item.type == "one") person.componen = One;
  if (item.type == "two") person.componen = Two;
}

onMounted(() => {});
</script>

子组件:

<template>
  <div>组件一</div>
  <el-input v-model="person.input"></el-input>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";

const person = reactive({ input: "" });
onMounted(() => {
  console.log("组件一");
});
</script>
<style scoped lang='less'>
</style>

效果:

这里会有警告:Vue received a Component that was made a reactive object. This can lead to unnecessary performance overhead and should be avoided by marking the component with `markRaw` or using `shallowRef` instead of `ref`. (Vue收到一个组件,该组件被设置为反应对象。这可能会导致不必要的性能开销,应该通过用“markRaw”标记组件或使用“shallowRef”而不是“ref”来避免。)

        

解决方法:

1.使用shallowRef替换响应式

<template>
  <div>
    <div v-for="item in person.data" :key="item" @click="btn(item)">
      {{ item.name }}
    </div>
    <h1>下面为动态组件</h1>
    <keep-alive>
      <component :is="componen"> </component>
    </keep-alive>
  </div>
</template>

<script setup>
import { reactive, onMounted, defineAsyncComponent, shallowRef } from "vue";
let componen = shallowRef(null);
const Two = defineAsyncComponent(() => import("./Two.vue"));
const One = defineAsyncComponent(() => import("./One.vue"));
let obj = shallowRef({
  Two,
  One,
});
const person = reactive({
  data: [
    { type: "one", name: "显示组件一" },
    { type: "two", name: "显示组件二" },
  ],
});
function btn(item) {
  if (item.type == "one") componen.value = obj.value.One;
  if (item.type == "two") componen.value = obj.value.Two;
}

onMounted(() => {});
</script>
<style scoped lang='less'>
</style>


http://www.kler.cn/a/152764.html

相关文章:

  • NoSQL 数据建模错误会降低性能
  • 【参数估计】---点估计之矩估计
  • Fiddler抓包工具之fiddler的介绍及安装
  • JVM 字节码
  • 基于vue+element-plus+echarts编写动态绘图页面
  • Visual Studio通过ClaudiaIDE插件设置背景图片
  • Star History 十月开源精选 |AI for Postgres
  • SSE接口的几种实现方式
  • 3D建模对制造企业的价值
  • 设计模式应用之java代码实现(一)
  • 前端知识笔记(十二)—————前端面试容易问到的问题总结
  • JVM类加载与运行时数据区
  • [读论文]meshGPT
  • Python 进阶(十二):随机数(random 模块)
  • 自动化设备如何实现远程监控?
  • 用HeidiSQL在MySQL中新建用户
  • Redis主从与哨兵架构详解
  • Eureka简单使用做微服务模块之间动态请求
  • 医疗健康行业企业文件管理软件推荐:提升管理效率与数据安全性
  • 每日一题:LeetCode-103/107.二叉树的(层序/锯齿形层序)遍历