web前端全系列 教程
1839个小节阅读:2243k
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在切换时创建新的组件实例通常是有意义的,但在这个例子中,我们的确想要组件能在被“切走”的时候保留它们的状态。要解决这个问题,我们可以用 <KeepAlive>
内置组件将这些动态组件包装起来
xxxxxxxxxx
<template>
<button @click="changeHandler">切换</button>
<keep-alive>
<component :is="activeComponent"></component>
</keep-alive>
</template>
<script>
import { ref } from "vue"
import ComponentA from "./ComponentA.vue"
import ComponentB from "./ComponentB.vue"
export default {
components:{
ComponentA,
ComponentB
},
setup() {
const activeComponent = ref("ComponentA")
function changeHandler() {
activeComponent.value = activeComponent.value === "ComponentA" ? "ComponentB" : "ComponentA"
}
return {
activeComponent,
changeHandler
}
}
}
</script>
xxxxxxxxxx
<template>
<h3>ComponentA</h3>
<button @click="addCount">countA:</button>
</template>
<script setup>
import { ref } from "vue"
const count = ref(0)
function addCount(){
count.value++
}
</script>
xxxxxxxxxx
<template>
<h3>ComponentB</h3>
<button @click="addCount">countA:</button>
</template>
<script setup>
import { ref } from "vue"
const count = ref(0)
function addCount() {
count.value++
}
</script>
<KeepAlive>
默认会缓存内部的所有组件实例,但我们可以通过 include
和 exclude
prop 来定制该行为
xxxxxxxxxx
<template>
<button @click="changeHandler">切换</button>
<keep-alive include="ComponentB">
<component :is="activeComponent"></component>
</keep-alive>
</template>
xxxxxxxxxx
<template>
<h3>ComponentB</h3>
<button @click="addCount">countA:</button>
</template>
<script setup>
import { ref,onActivated, onDeactivated } from "vue"
const count = ref(0)
function addCount() {
count.value++
}
onActivated(() => {
// 调用时机为首次挂载
// 以及每次从缓存中被重新插入时
console.log("加入");
})
onDeactivated(() => {
// 在从 DOM 上移除、进入缓存
// 以及组件卸载时调用
console.log("移除");
})
</script>
实时效果反馈
1. 在Vue组件中,下列那个是缓存生命周期函数:
A created
B mounted
C updated
D activated
答案
1=>D