<div id="app">
<!-- 为了避免频繁的创建,消耗较大的常用组件,缓存时正解,ABC组件的频繁创建 -->
<!-- 根目录如果时router-view可用router-view -->
<keep-alive :include="cached" :exclude="noCached">
<aa v-if="current==='A'"></aa>
<bb v-if="current==='B'"></bb>
<cc v-if="current==='C'"></cc>
</keep-alive>
<button @click="current= 'A'">A存在,销毁BC</button>
<button @click="current= 'B'">B存在,销毁AC</button>
<button @click="current= 'C'">C存在,销毁AB</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
//常用页面的缓存设计
//产品设计:项目长时间不关,导致内存占用,使用比较卡
//需求设计:了解用户常用的页面
//A用户的常用页面可能和B用户不同
//有必要在埋点的时候,记录用户常用浏览页面,并保存到数据库
//页面加载的时候动态获取就是下方这两个值可以由后端获取,让用户经常浏览的页面缓存起来下次打开更快
const cached=['aa','bb']; //缓存时根据【组件名】 不是route中的name
const noCached=['cc'];
//当前有3个组件,请你想成300个页面
//会在用户的使用下进行切换,toB,长时间不关闭
let AComponent={
template:`
<button>AA</button>
`,
beforeDestroy(){
console.log('A组件被销毁了');
}
}
let BComponent={
template:`
<button>BB</button>
`,
beforeDestroy(){
console.log('B组件被销毁了');
}
}
let CComponent={
template:`
<button>CC</button>
`,
beforeDestroy(){
console.log('c组件被销毁了');
}
}
Vue.component('aa',AComponent)
Vue.component('bb',BComponent)
Vue.component('cc',CComponent)
new Vue({
el:'#app',
data(){
return{
current:'A',
cached,
noCached
}
}
})
</script>
keep-alive的使用场景
最新推荐文章于 2024-02-04 19:30:00 发布