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>

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_63701303

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值