keep-alive是Vue的內置組件陪汽,能在組件切換過程中將狀態(tài)保留在內存中,防止重復渲染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()
}
}