1.vue3使用component动态组件,并使用ref来调用子组件的属性或方法
使用vue3动态组件的时候,需要使用shallowRef或者markRaw进行包裹组件,用于动态切换组件,不然会报错 App.vue:12 [Vue warn]: Vue received a Component which 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
.
<template>
<div>
<button
v-for="(item,index) in tabs"
:key="index"
@click="switch(item)"
>
{{ item.name}}
</button>
<!-- 使用component标签来渲染动态组件 -->
<component :is="currentComponent" ref="dynamicComponent"></component>
<button @click="callMethod">调用动态组件的方法</button>
</div>
</template>
<script setup lang="ts">
import {
reactive,
ref,
shallowRef,
markRaw,
nextTick
} from "vue";
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
const tabs = [
{
name: "comp1",
com: markRaw(ComponentA),
},
{
name: "comp2",
com: markRaw(ComponentB),
},
];
let activeComp=ref(null)
let currentComponent= shallowRef(ComponentA );
const dynamicComponent= ref(null);
//调用方法
const callMethod =()=>{
if (activeComp.value== "comp2") {
dynamicComponent.value.getData();
}
}
//切换
const switch=(item)=>{
currentComponent.value = item.comp;
activeComp.value=item.name
//切换后调用组件方法
nextTick(() => {
if (activeComp.value== "comp2") {
dynamicComponent.value.getData();
}
});
}
</script>