需求:點擊首頁列表進入二級頁面,返回的時候保持在原位置。
keep-alive是Vue的內置組件,能在組件切換過程中將狀態保留在內存中,防止重復渲染DOM。
1:App.vue
<template> <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> </template>
2:router / index.js
export default new Router({ routes: [ { path: '/', name: 'home', component: Home, meta: { keepAlive: true // 需要緩存 } },{ path: '/home', name: 'home', component: Home, meta: { keepAlive: true // 需要緩存 } }, ... ] scrollBehavior(to, from, savedPosition) { //解決拖動時多個頁面互相影響的問題,當切換到新路由時,想要頁面滾到頂部 // if (savedPosition) { // return savedPosition // } else { // if (from.meta.keepAlive) { // from.meta.savedPosition = document.body.scrollHeight // } // } // return { // x: 0, // y: 0 // } } })
3:home.vue
3.1:定義初始滾動高度
data() { return { scrollY:0, } },
3.2:注意這里一定是滾動的元素是
.container
.container { position: absolute; top: 0;bottom: 0; width: 100%; padding: 0;margin:0; overflow: hidden; overflow-y: scroll; }
3.3:重點!! (不用放在methods里)
//記錄離開時的位置 beforeRouteLeave (to, from, next) { //保存滾動條元素div的scrollTop值 this.scrollY = document.querySelector('.container').scrollTop // console.log(this.scrollY) next() }, // 為div元素重新設置保存的scrollTop值 beforeRouteEnter (to, from, next) { next(vm => { // vm = this document.querySelector('.container').scrollTop = vm.scrollY // console.log( document.querySelector('.container').scrollTop ) }) },
本人在移動端親測代碼: 親測有效,一定要弄清楚是哪個元素在滾動,不要直接用winodow去監聽,直接用滾動的元素去監聽才能監聽到scrollTop
html:
<div class="newVipClass" > <div class="recordContent"> <!--這個才是滾動元素元素需要監聽,scrollTop才能獲取到,我最外面的元素是fiexed定位的,永遠獲取不到scroll--> ... </div> </div>
js:
data: { box: '', scrollY: '' } mounted: { // 監聽scroll變化 this.$nextTick(()=>{ this.box = document.querySelector('.recordContent') this.box.addEventListener('scroll', function(){ this.scrollY = document.querySelector('.recordContent').scrollTop console.log("scrollY", this.scrollY) }, false) }) }, beforeRouteEnter (to, from, next) { next(vm => { //因為當鈎子執行前,組件實例還沒被創建 // vm 就是當前組件的實例相當於上面的 this,所以在 next 方法里你就可以把 vm 當 this 來用了。 console.log(vm);//當前組件的實例 if (from.name == 'monthCarApplyDetal' && to.name == "newMonthApply") { to.meta.title = "編輯月卡申請" } // 為div元素重新設置保存的scrollTop值 document.querySelector('.recordContent').scrollTop = vm.scrollY }); }, //記錄離開時的位置 beforeRouteLeave (to, from, next) { //保存滾動條元素div的scrollTop值 this.scrollY = document.querySelector('.recordContent').scrollTop console.log('離開時保存滾動條的位置', this.scrollY) next() },
小伙伴們還有啥好方法,歡迎分享!!!