vant list元件滾動保留滾動條位置
阿新 • • 發佈:2021-09-14
vant list元件滾動保留滾動條位置,需結合keepAlive使用,分享此篇,供大家參考。
1、儲存位置的前提是用的keepAlive元件來做快取,app.程式碼
<template> <div id="app"> <keep-alive> <router-view v-if='$route.meta.keepAlive'/> </keep-alive> <router-view v-if='!$route.meta.keepAlive'/> </div> </template>
2、在路由檔案router.,給每個路由meta新增www.cppcns.comscrollTop和keepAlive
{ path: '/home',name: 'home',component: resolve => require(['@/views/home/index.vue'],resolve),www.cppcns.commeta: { title: '首頁',index: 1,keepAlive: true,scrollTop: 0 } },{ path: '/classify',name: 'classify',component: resolve => require(['@/views/classify/index.vue'],meta: { title: '分類',{ path: '/shopping',name: 'shopping',component: resolve => require(['@/views/shopping/index.vue'],meta: { title: '購物車',index: 1,{ path: '/detail',name: 'detail',component: resolve => require(['@/views/detail/index.vue'],meta: { title: '詳情',index: 2,// keepAlive: true,// scrollTop: 0 } },
3、然後在main.js,記錄滾動條的位置
router.beforeEach((to,from,next) => { if (from.meta.keepAlive) { const $wrapper = document.querySelector('.app-wrapper'); // 列表的外層容器 注意找到滾動的盒子 const scrollTop = $wrapper ? $wrapper.scrollTop : 0; console.log('scrollTop=',scrollTop) from.meta.scrollTop = scrollTop; } next();});
4、最後在需要記錄保留滾動條位置的地方獲取通過activated(這個函式每次進入頁面都會執行,只有結合使用keepAlive元件才有效)來獲取scrollTop
activated () { const scrollTop = this.$route.meta.scrollTop; const $wrapper = document.querySelector('.app-wrapper'); if (scrollTop && $wrapper) { $wrapper.scrollTop = scrollTop; } },
比如快取了某些頁面也不想隨之滾動,則把scrollTop置0即可;
activated() { const $wrapper = document.querySelector(".app-wrapper"); $wrappVjLfYPJbper.scrollTop = 0; },
注意,頁面滾動的話,其他頁面有滾動條的也會隨之滾動,可以對其他頁面裡面處理,或者判斷是否從詳情頁到列表頁來判斷是否快取位置,如果不是,則回到頂部,但是注意路由鉤子函式this的使用;