這是一個(gè)實(shí)現(xiàn)上拉加載和下拉刷新功能的頁面,這里用了vue-infinite-scroll插件,需要實(shí)現(xiàn)返回頁面時(shí)頁面可以自動(dòng)滑動(dòng)到上次滑動(dòng)的位置。具體實(shí)現(xiàn)方式如下:
1、在App.vue文件中設(shè)置緩存組件keep-alive
<!-- 緩存組件跳轉(zhuǎn)的頁面 -->
<keep-alive>
<router-view v-if="$route.meta.keepAlive" transition-mode="out-in"></router-view>
</keep-alive>
<!-- 非緩存組件跳轉(zhuǎn)頁面 -->
<router-view v-if="!$route.meta.keepAlive" transition-mode="out-in"></router-view>
2、路由文件中給需要記錄滾動(dòng)位置的頁面設(shè)置keepAlive: true
{
path: '/Info',
name: 'InfoList',
component: InfoList,
meta: {
keepAlive: true
}
}
3、在頁面注冊對應(yīng)的事件
(1)在data中定義一個(gè)初始值 scroll
(2)在mouted中 ,mouted中的方法代表dom已經(jīng)加載完畢
mounted() {
window.addEventListener('scroll', this.handleScroll)
}
(3)methods 用于存放頁面函數(shù)
handleScroll () {
this.scroll = document.documentElement && document.documentElement.scrollTop
console.log(this.scroll)
}
4、activated 為keep-alive加載時(shí)調(diào)用
activated() {
if(this.scroll > 0) {
window.scrollTo(0, this.scroll); this.scroll = 0;
window.addEventListener('scroll', this.handleScroll);
}
}
5、deactivated 頁面退出時(shí)關(guān)閉事件 防止其他頁面出現(xiàn)問題
deactivated(){
window.removeEventListener('scroll', this.handleScroll);
}
keep-alive和上拉加載組件infinite-scroll一起使用時(shí),其他子組件會(huì)觸發(fā)infinite-scroll
在deactivated里面將屬性infinite-scroll-disabled設(shè)置為true