父组件
<template>
<div>
<component :is="ddd('a')"></component>
<div v-if="show">其他元素</div>
<div @click="show = !show">点击</div>
</div>
</template>
<script setup lang="ts">
import { defineAsyncComponent } from "vue";
//这里的name必须由外面传递
const ddd = (name) => {
return defineAsyncComponent(
async () => await import(`./${name}.vue`),
);
};
const show = ref(false)
</script>
子组件:
<script setup lang="ts">
import { onMounted } from "vue"
onMounted(() => {
console.log('触发mounted')
})
</script>
<template>
<p class="read-the-docs">测试1</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
导致子组件mounted
一直触发的原因是什么?keepAlive
好像也没有作用?
在线demo
ddd
改成静态对象,不然每次都会返回一个新的构造器,VNodeType
不一致,组件就会重新走一遍unmount
、mount