父组件
<template>
<keep-alive>
<A v-if="show" />
<B v-else />
</keep-alive>
<button @click="show = !show">切换</button>
</template>
<script setup>
import { ref } from 'vue'
import A from './components/A.vue'
import B from './components/B.vue'
const show = ref(true)
</script>
<style scoped></style>
子组件
<template>
<div>A</div>
<input type="text" v-model="value" />
</template>
<script setup lang="ts">
import { ref, onMounted, onActivated, onDeactivated, onUnmounted } from 'vue'
const value = ref('')
onMounted(() => {
console.log('A mounted') // 只会触发一次
})
onActivated(() => {
console.log('A activated') // 每次进入组件都会触发
})
onDeactivated(() => {
console.log('A deactivated') // 每次离开组件都会触发
})
onUnmounted(() => {
console.log('A unmounted')
})
</script>
<style scoped lang="scss"></style>