vue中進入詳情頁記住列表滾動位置keep-alive解決

一、配置路由 keepactice:true

  {
     	 path: '/index',
     	 name: 'index',
     	 component: index,
     	 meta: {
       		 keepalive: true // 組件是否需要被保存
     	 }
    }

二、在App.vue頁面當中,將需要保存的組件通過路由標籤router-view,寫在keep-alive標籤裏(區分keepalive大小寫

<div id="app">
    <keep-alive>
        <router-view v-if="$route.meta.keepalive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepalive"></router-view>      
</div>

App.js設置記住滾動的值:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

const store = new Vuex.Store({
	state: {
	    top: 0 //滾動條初始位置
	},
	mutations: {
	      setHomeListTop(state, top) {
	        state.top = top;
	      },
	},
	actions: {
	    setListTop(context, status) {
	        context.commit("setHomeListTop", status);
	    },
	}
});
export default store;

三、在組件中使用

<div class="order-list" ref="scroll">
</div>
export default {
    methods: {
        recordScrollPosition(e) {
	    let top= e.target.scrollTop;
	    this.$store.state.top = top;
	}
    },
    mounted() {
	let that = this;
	this.$nextTick(() => {
		this.$refs.scroll.addEventListener("scroll", that.recordScrollPosition, true);
	});
    },
    activated() {//keep-alive加載時調用
	this.$refs.scroll.scrollTop = this.$store.state.top;
	let that = this;
	this.$refs.scroll.addEventListener("scroll", that.recordScrollPosition, true);
    },
    deactivated() { //頁面退出時關閉事件 防止其他頁面出現問題
	let that = this;
	this.$refs.scroll.removeEventListener("scroll", that.recordScrollPosition, true);
    }

}

 

發佈了94 篇原創文章 · 獲贊 42 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章