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>
相关推荐
伍哥的传说几秒前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
ai产品老杨3 分钟前
解锁仓储智能调度、运输路径优化、数据实时追踪,全功能降本提效的智慧物流开源了
javascript·人工智能·开源·音视频·能源
GDAL3 分钟前
Quat.js四元数完全指南
javascript·quaternion
alphageek87 分钟前
Electron开源库入门教程:跨平台桌面应用框架
javascript·其他·electron·开源
小桥风满袖39 分钟前
极简三分钟ES6 - ES8中字符串扩展
前端·javascript
张拭心39 分钟前
这就是流量的力量吗?用豆包 AI 编程做的xhs小组件帖子爆了
前端·ai编程·豆包marscode
少年阿闯~~43 分钟前
CSS3的新特性
前端·javascript·css3
IT_陈寒1 小时前
React性能优化:这5个Hook技巧让我的组件渲染效率提升50%(附代码对比)
前端·人工智能·后端
智能化咨询1 小时前
【Linux】【实战向】Linux 进程替换避坑指南:从理解 bash 阻塞等待,到亲手实现能执行 ls/cd 的 Shell
前端·chrome