1. 程式人生 > >vue中 進入詳情頁記住滾動位置(keep-alive)

vue中 進入詳情頁記住滾動位置(keep-alive)

vue中 進入列表詳情計算滾動位置

> 有時業務提出這樣一個需求 就是從商品頁面進入到列表詳情頁 要儲存當前滾動的位置,這裡我就想到了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);
    }