> 有時業(yè)務(wù)提出這樣一個需求 就是從商品頁面進入到列表詳情頁 要保存當前滾動的位置,這里我就想到了keep-alive
1.首先在路由中引入需要的模塊
{ path: ‘/scrollDemo', name: ‘scrollDemo', meta: { keepAlive: true // 需要緩存 }, component: resolve => { require([‘../view/scrollDemo.vue'], resolve) } }
2.在App.vue中設(shè)置緩存組件
<keep-alive> // 緩存組件跳轉(zhuǎn)的頁面 <router-view v-if="$route.meta.keepAlive" class="ui-view" transition-mode="out-in"></router-view> </keep-alive> // 非緩存組件跳轉(zhuǎn)頁面 <router-view v-if="!$route.meta.keepAlive" class="ui-view" transition-mode="out-in"></router-view>
3.在頁面注冊對應(yīng)的事件
1. 在return中定義一個初始值 scroll
2. 在mouted中 ,mouted中的方法代表dom已經(jīng)加載完畢
window.addEventListener('scroll', this.handleScroll);
3.methods 用于存放頁面函數(shù)
handleScroll () { this.scroll = document.documentElement && document.documentElement.scrollTop console.log(this.scroll) }
4. activated 為keep-alive加載時調(diào)用
activated() { if(this.scroll > 0){ window.scrollTo(0, this.scroll); this.scroll = 0; window.addEventListener('scroll', this.handleScroll); } }
5.deactivated 頁面退出時關(guān)閉事件 防止其他頁面出現(xiàn)問題
deactivated(){ window.removeEventListener('scroll', this.handleScroll); }
以上這篇vue中進入詳情頁記住滾動位置的方法(keep-alive)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com