vue3使用动态component

使用场景:

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

使用方法:

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

2.component中的is属性

父组件:

html 复制代码
<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>

子组件:

html 复制代码
<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替换响应式

html 复制代码
<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>
相关推荐
电商API&Tina7 分钟前
1688 拍立淘接口(item_search_img)测试与接入实战心得
java·大数据·前端·物联网·oracle·json
不想说话的麋鹿23 分钟前
「性能优化」虚拟列表极致优化实战:从原理到源码,打造丝滑滚动体验
前端·vue.js·面试
ouzz24 分钟前
使用 react-canvas 制作一个 Figma 工具:从画布到编辑器
前端·javascript
万少27 分钟前
AI 智能记账 Skill,基于飞书 CLI + 多维表格构建。
前端
颜酱28 分钟前
语音合成与视觉模型api接入实现
前端·javascript·人工智能
你听得到1130 分钟前
Get 这波之后,我把 Flutter 状态管理重新看了一遍:新项目到底该选谁?
前端·flutter·架构
一天睡25小时1 小时前
做产品前,先别急着写代码:我是怎么判断一个点子值不值得做的
前端
霍理迪1 小时前
TS—函数、类、泛型
前端
一 乐1 小时前
工会管理|基于springboot + vue工会管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·工会管理系统
cc.ChenLy1 小时前
浏览器缓存机制详解:如何彻底解决前端代码更新后的缓存问题
前端