使用keep-alive包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们
场景:按钮控制组件是否显示,显示的组件内部进行样式更改(例如点击按钮改变颜色),当子组件显示时,按钮控制改变颜色后,父组件控制子组件显示隐藏,每次切换子组件(销毁,创建)样式无法进行保存,加上keep-alive后,子组件样式更改,切换显示隐藏后样式依旧存在
<!--父组件 -->
<template>
<div id="example">
<!-- <BB v-if="showBB"></BB> -->
<keep-alive><BB v-if="showBB"></BB></keep-alive>
</div>
</template>
<script>
import BB from "./bb";
export default {
data() { return { showBB: true };},
methods: {
change2() {this.showBB = !this.showBB;},
},
components: { BB,},
};
</script>
<!--子组件 -->
<template>
<div>
<div ref="aaa">颜色改变</div>
<button @click="aa">改颜色</button>
</div>
</template>
<script>
export default {
methods: {
aa() {this.$refs.aaa.style.color = "blue";},
},
};
</script>
keep-alive生命周期
keep-alive后组件不会销毁,则created只会执行初始化一次,即使切换后也不会再次执行,对应自身两个周期
- activated 激活时
- deactivated 失效时
<script>
export default {
activated() {
//每次调用都执行
console.log("B组件渲染activated");
},
deactivated() {
//每次调用都执行
console.log("B组件卸载deactivated");
},
created() {
//只会执行一次
console.log("B组件渲染create");
},
};
</script>
keep-alive设置 缓存的组件,不需要缓存的组件,以及最大缓存多少个组件,需要配合name 场景:多个组件再keep-alive中有些组件需要缓存有些组件不需要缓存
- include 需要缓存的组件
- exclude 不需要缓存的组件
- max缓存组件的上限
- 语法:字符串include="a,b" 正则:include="/a|b/" 数组:include="['a', 'b']"
不使用以上方法则默认全部缓存,使用了include后,未再include定义的则全部不缓存,反之exclude一样
例子:
<template>
<div>
<button @click="change">显示include1</button>
<button @click="change2">显示include2</button>
<keep-alive exclude="include1" max="2">
<component :is="currentView"></component
></keep-alive>
</div>
</template>
<script>
import In1 from "./include1";
import In2 from "./include2";
export default {
name: "include",
data() {return { currentView: In1 }},
methods: {
change() {this.currentView = In1},
change2() {this.currentView = In2}
},
components: { In1, In2 },
};
</script>
<!-- include1 -->
<template>
<div><div ref="aaa">include1</div><button @click="aa">include1</button></div>
</template>
<script>
export default {
name: "include1",
methods: {aa() {this.$refs.aaa.style.color = "blue"}},
};
</script>
<!-- include2 -->
<template>
<div><div ref="aaa">include2</div><button @click="aa">include2</button></div>
</template>
<script>
export default {
name: "include2",
methods: {aa() {this.$refs.aaa.style.color = "red"}}
};
</script>