使用场景:
多个组件通过component
标签挂载在同一个组件中,通过触发时间进行动态切换。vue3与vue2用法不一样,这里有坑!
使用方法:
1.通过vue的defineAsyncComponent
实现挂载组件
父组件:
<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”来避免。)
<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>
原文地址:https://blog.csdn.net/m0_63701303/article/details/134719054
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_41614.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。