vue keep-alive 实现详情返回列表保留页面数据
實(shí)現(xiàn)功能
詳情頁(yè)返回列表頁(yè),列表頁(yè)保留上次瀏覽位置
其它頁(yè)面進(jìn)入到列表表,列表頁(yè)刷新
當(dāng)詳情頁(yè)有數(shù)據(jù)改變時(shí),列表頁(yè)也要更新該條數(shù)據(jù)
實(shí)現(xiàn)思路
用keep-alive保留列表頁(yè)面數(shù)據(jù)
activated鉤子函數(shù)來(lái)更新數(shù)據(jù)
利用路由守衛(wèi)判斷是否從詳情頁(yè)返回來(lái)決定是否更新數(shù)據(jù)
當(dāng)詳情數(shù)據(jù)改變時(shí),返回列表后利用vm.$set(vm.list,index,newValue)或vm.list.splice(i,1)進(jìn)行更新
具體實(shí)現(xiàn)
1. 設(shè)置keepalive
App.vue
<keep-alive>
<router-view v-if="$route.meta.keepAlive">
</router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />
router/index.js
{
path: ...,
name: ...,
meta: {
title: '列表',
keepAlive: true,
canKeep:false
},
component: ...
},
2. 在列表頁(yè)路由守衛(wèi)判斷是否保留數(shù)據(jù),只在詳情返回做保留
beforeRouteEnter(to, from, next) {
if (from.name == "detail") {
to.meta.canKeep = true;
} else {
to.meta.canKeep = false;
}
next();
},
3. 在activated中更新數(shù)據(jù)
activated() {
if (!this.$route.meta.canKeep) {
// 在這里發(fā)送請(qǐng)求,刷新數(shù)據(jù)
}
},
4. 列表更新單條數(shù)據(jù)
activated() {
// 刷新數(shù)據(jù)
if (!this.$route.meta.canKeep) {
...
window.scrollTo(0, 1);
} else {
// 不刷新數(shù)據(jù) 但詳情頁(yè)數(shù)據(jù)有更改時(shí)
this.showPackageList.forEach((item,idx) => {
if(..){
item.looked = true;
// 更新某一條數(shù)據(jù)
this.$set(this.showPackageList, idx, item);
}
})
}
this.rollingLoad();
},
遇到問(wèn)題
從詳情1返回列表時(shí)正常,進(jìn)入其它頁(yè)面,返回,列表數(shù)據(jù)更新,進(jìn)入詳情2,返回列表,此時(shí)列表會(huì)自動(dòng)定位到從列表進(jìn)入詳情1時(shí)的位置,而不是進(jìn)入詳情2前的位置。
原因
列表只做了數(shù)據(jù)刷新,位置信息依舊保留,當(dāng)列表刷新后,如果頁(yè)面觸發(fā)過(guò)滾動(dòng),位置信息得到更新,再次返回則正常,無(wú)觸發(fā)滾動(dòng)則再次返回會(huì)回到第一次定位的位置
解決方法
在列表數(shù)據(jù)更新后,手動(dòng)觸發(fā)滾動(dòng)
activated() {
if (!this.$route.meta.canKeep) {
// 刷新數(shù)據(jù)
// 重置頁(yè)面位置
window.scrollTo(0,1)
}
},
以上就是keep-alive 實(shí)現(xiàn)詳情返回列表保留頁(yè)面數(shù)據(jù)。。。。
總結(jié)
以上是生活随笔為你收集整理的vue keep-alive 实现详情返回列表保留页面数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: html5音频文件生成波形图代码,HTM
- 下一篇: 风之大陆圣痕选择是什么