keep-alive是Vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。
使用示例:
<template>
<div id="app">
<keep-alive>
<!--显示的是当前路由地址所对应的内容-->
<router-view/>
</keep-alive>
</div>
</template>
路由中的内容被加载过一次后,就会把路由中的内容放在内存中,下次再进这个路由,不需要重新渲染组件。
当使用keep-alive组件的时候,会多出2个生命周期的方法activated
和deactivated
,当页面重新显示的时候会调用activated
,我们可以在这个方法中做判断,是否使用内存中的内容。
例如:
methods: {
getHomeInfo () {
axios.get('/api/index.json?city=' + this.city)
.then(this.getHomeInfoSucc)
},
getHomeInfoSucc (res) {
}
},
activated () {
if (this.lastCity !== this.city) {
this.lastCity = this.city
this.getHomeInfo()
}
}