0
点赞
收藏
分享

微信扫一扫

vue中keep-alive详细讲解

最后的执着 2022-09-01 阅读 92
场景

今天产品跑过来跟我说,
当我在A页面修改数据后,去B页面。
然后返回A页面。希望A页面保留我修改后的数据。
而不是数据又恢复最初的样子了。我心里想,尼玛,又要加班了?
看下面小粒子

数据被被重置的问题

<template>
<div>
<el-button @click="gotosHander">去详情页面</el-button>
<el-button @click="changeHander">改变数据</el-button>
<ul class="box">
<li class="demoli" v-for="(item,index) in list" :key="index">
{{ item.name }}==> {{item.age }}
</li>
</ul>
</div>
</template>
<script>
export default {
data(){
return{
list:[
{name:'张三',age:23},
{name:'李四',age:33},
]
}
},
methods:{
gotosHander(){
this.$router.push("/details")
},
changeHander(){
this.list=[
{name:'何西亚',age:33},
]
}
}
}
</script>

vue中keep-alive详细讲解_数据

我们发现的问题

在页面更改数据后,我们去详情页面。
在返回上一个页面。数据被重置了。
但是我们并不想数据重置。
想让他保留我们更改后的样子,
怎么办?????

使用keep-alive解决数据被重置

<keep-alive>
<router-view></router-view>
</keep-alive>

vue中keep-alive详细讲解_缓存_02

在页面中使用一个定时器

<template>
<div>
<el-button @click="gotosHander">去详情页面</el-button>
</div>
</template>
<script>
export default {
data(){
return{
timer:null
}
},

methods:{
gotosHander(){
this.$router.push("/details")
},
},
mounted(){
this.timer=setInterval(()=>{
console.log("@@@@@@@@@@@@@@@@@@@")
},100)
},
beforeDestroy(){
clearInterval(this.timer)
}
}
</script>

vue中keep-alive详细讲解_数据_03

keep-alive产生的问题

如果我们在页面中写一个定时器,
那么这个定时器在beforeDestroy中将不会被清除。
也就是说:使用keep-alive后,页面中的beforeDestroy不会被执行

如何让页面中的beforeDestroy被执行

我们可以使用生命周期 activated 和 deactivated

activated是页面或者组件被激活的时候触发该函数,
激活可以理解为展示在页面上的时候。

deactivated是页面别取消隐藏的时候触发该函数
我们从详情页进入该页面的时候,

使用activated函数。因为是展示嘛~
当我们离开该页面的时候触发函数deactivated,因为是隐藏嘛~

从详情页进入该页面

<template>
<div>
<el-button @click="gotosHander">去详情页面</el-button>
</div>
</template>
<script>
export default {
data(){
return{
timer:null
}
},

methods:{
gotosHander(){
this.$router.push("/details")
},
},
mounted(){
this.timer=setInterval(()=>{
console.log("@@@@@@@@@@@@@@@@@@@")
},100)
},
activated(){
console.log("页面被激活的时候触发该函数")
},
deactivated(){
clearInterval(this.timer)
console.log("页面被取消/切换的时候触发该函数")
},
}
</script>

vue中keep-alive详细讲解_数据_04

keep-alive的后遗症

刚刚我们说了,使用keep-alive后,默认情况下,
所有页面中的beforeDestroy和destroyed生命周期函数不会被执行了
我的个乖乖~,好可怕!
其实也不是没有办法,只是我们使用include。
include只会缓存与之匹配的值

include的使用

<keep-alive  include="yourPageName">
<router-view></router-view>
</keep-alive>
上面这段代码只会缓存【页面、组件】名是yourPageNamede

如果你需要缓存多个页面或者组件。
你可以写成一个数组
<keep-alive :include="['yourPageName','xingqing']">
<router-view></router-view>
</keep-alive>


<template>
<div>
<el-button @click="backHander">返回上一页</el-button>
我是详情页面
</div>
</template>

<script>
export default {
//这个是组件或者页面名。
// 因为include会自动匹配,该组件会被缓存
// 所以销毁的生命周期是不会被执行的
// activated【激活、展示】 和 deactivated【隐藏、离开】会被执行
name:'xingqing',
}
</script>

遇见问题,这是你成长的机会,如果你能够解决,这就是收获。


作者:晚来南风晚相识

如果文中有什么错误,欢迎指出。以免更多的人被误导。



举报

相关推荐

0 条评论