1楞抡、在想要緩存滑動高度的頁面加入一下代碼
beforeRouteLeave(to, from, next) {
? ? this.$route.meta.scrollHeight = document.documentElement.scrollTop
? ? next();
}
切換路由之前獲取頁面的高度执桌,并存入當(dāng)前路由的meta中(scrollHeight為自定義key)
2舍沙、存入滑動高度后,在路由管理頁面(Router下的index.js頁面)加入路由跳轉(zhuǎn)監(jiān)聽
router.beforeEach((to, from, next) => {
? ? ?next();
?????if(to.meta.scrollHeight) {
? ? ? ? ? ? document.documentElement.scrollTop = to.meta.scrollHeight
? ? ?}
})
查看將要跳轉(zhuǎn)的路由(to)是否含有scrollHeight這個字段,如果有就改變頁面高度杆煞,沒有就跳過
如果出現(xiàn)部分頁面不生效需要用setTimeout把document.documentElement.scrollTop = to.meta.scrollHeight包起來
setTimeout(()=>{
? ??document.documentElement.scrollTop = to.meta.scrollHeight
})
3、這種方法適用于可以獲取到?document.documentElement.scrollTop 的項目蘑险,如果項目整個頁面的根節(jié)點是position定位后固定為height: 100%; width: 100%的滴肿,就需要改變獲取相應(yīng)元素的scrollTop,同時也需要改變router.beforeEach中相應(yīng)元素的scrollTop賦值
4佃迄、這種方法不僅僅限于meta存儲泼差,相應(yīng)的還有?localStorage、vuex呵俏,針對于想要整個項目關(guān)閉后再次打開項目還想要關(guān)閉前的滑動距離堆缘,就需要用?localStorage 來存儲,vuex和meta存儲都只是暫時的普碎,但是meta存儲是最簡單的吼肥,相對于其他兩種不需要遍歷,不需要重新獲取麻车,不需要校驗路由是否相同
5缀皱、也可以參考VueKeepScrollPosition包(并不是每個項目都會生效)
安裝VueKeepScrollPosition:
? ??????npm i? vue-keep-scroll-position
引入VueKeepScrollPosition:
? ? ? ? main.js寫入:import VueKeepScrollPosition from 'vue-keep-scroll-position'????Vue.use(VueKeepScrollPosition)
使用VueKeepScrollPosition:
? ??????<router-view v-keep-scroll-position></router-view>
原理:通過路由變化監(jiān)聽頁面滑動距離并進行存儲,在頁面再次訪問后獲取存儲的滑動距離动猬,并改變頁面的scrollTop