<keep-alive> </keep-alive> 默认全部加载过得全部缓存
include 那些缓存 ====>可以写组件名也可以写正则表达式
举例:
<keep-alive :include="box"> box为变量include前面+:,不是变量前面不加
</keep-alive>===>只有box被缓存了
exclude 那些不缓存
max 最多缓存几个组件 ===>最多缓存多少组件,缓存最近被渲染过的几个组件一旦数字达到了,最近被创建的组件就会被销毁
举例:
<keep-alive :max="2">
</keep-alive>====>最近被访问的两个组件会被缓存
动态组件的切换,切换后是不会缓存之前被切换掉的组件的,每次切换新组件的时候,Vue 都创建了一个新的组件对象。有时候我们希望在A组件时用户做了一些操作,切换B组件时做了一些操作,当切回A组件时希望记住A的操作,不要重新创建A组件,keep-alive可以缓存动态切换的组件
举例:
<template>
<div class="box">
<div class="one">
<button @click="fn('tbos')">切换页面1</button>
<button @click="fn('box2')">切换页面2</button>
<keep-alive>//所有的都缓存
<components :is="name"></components>
</keep-alive>
</div>
<div class="two">
<button @click="fm('box3')">box3页面</button>
<button @click="fm('box4')">box4页面</button>
<keep-alive exclude="box3">//不包含box3的缓存
<components :is="name2"></components>
</keep-alive>
</div>
<div class="three">
<button @click="fmn('box2')">box2页面</button>
<button @click="fmn('box4')">box4页面</button>
<keep-alive include="box2">//包含box2的缓存
<components :is="name3"></components>
</keep-alive>
</div>
<div class="four">
<button @click="fmn2('tbos')">切换页面1</button>
<button @click="fmn2('box2')">box2页面</button>
<button @click="fmn2('box3')">box3页面</button>
<button @click="fmn2('box4')">box4页面</button>
<keep-alive max="2">//包含最近两个的缓存
<components :is="name4"></components>
</keep-alive>
</div>
</div>
</template>
<script>
import tbos from "./components/tbos.vue"
import box2 from "./components/box2.vue"
import box3 from "./components/box3.vue"
import box4 from "./components/box4.vue"
export default {
data() {
return {
name: "tbos",
name2: "box3",
name3:"box2",
name4:"tbos"
}
},
methods: {
fn(e) {
this.name = e
},
fm(e) {
this.name2 = e
},
fmn(e){
this.name3 = e
},
fmn2(e){
this.name4 = e
},
},
components: {
tbos,
box2,
box3,
box4
}
}
</script>
<style>
.box {
width: 800px;
height: 400px;
border: 1px solid black;
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
}
.one {
width: 400px;
height: 200px;
background-color: aquamarine;
}
.two {
width: 400px;
height: 200px;
background-color: blueviolet;
}
.three {
width: 400px;
height: 200px;
background-color: rgb(43, 183, 109);
}
.four {
width: 400px;
height: 200px;
background-color: rgb(145, 222, 45);
}
</style>
activated desactivated 只能在keep-active中使用