> 有時業務提出這樣一個需求 就是從商品頁面進入到列表詳情頁 要保存當前滾動的位置,這里我就想到了keep-alive
1.首先在路由中引入需要的模塊
{ path: ‘/scrollDemo', name: ‘scrollDemo', meta: { keepAlive: true // 需要緩存 }, component: resolve => { require([‘../view/scrollDemo.vue'], resolve) } }2.在App.vue中設置緩存組件
<keep-alive> // 緩存組件跳轉的頁面 <router-view v-if="$route.meta.keepAlive" class="ui-view" transition-mode="out-in"></router-view> </keep-alive> // 非緩存組件跳轉頁面 <router-view v-if="!$route.meta.keepAlive" class="ui-view" transition-mode="out-in"></router-view>
3.在頁面注冊對應的事件
1. 在return中定義一個初始值 scroll
2. 在mouted中 ,mouted中的方法代表dom已經加載完畢
window.addEventListener('scroll', this.handleScroll);3.methods 用于存放頁面函數
   handleScroll () {    this.scroll = document.documentElement && document.documentElement.scrollTop    console.log(this.scroll)   }4. activated 為keep-alive加載時調用
   activated() {     if(this.scroll > 0){      window.scrollTo(0, this.scroll);      this.scroll = 0;      window.addEventListener('scroll', this.handleScroll);     }  }5.deactivated 頁面退出時關閉事件 防止其他頁面出現問題
  deactivated(){   window.removeEventListener('scroll', this.handleScroll);  }以上這篇vue中進入詳情頁記住滾動位置的方法(keep-alive)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選