vant list组件滚动保留滚动条位置
vant list组件滚动保留滚动条位置,需结合keepAlive使用,分享此篇,供大家参考。
1、保存位置的前提是用的keepAlive组件来做缓存,app.vue代码
<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.js,给每个路由meta添加scrollTop和keepAlive
{
path: '/home',
name: 'home',
component: resolve => require(['@/views/home/index.vue'], resolve),
meta: {
title: '首页',
index: 1,
keepAlive: true,
scrollTop: 0
}
},
{
path: '/classify',
name: 'classify',
component: resolve => require(['@/views/classify/index.vue'], resolve),
meta: {
title: '分类',
index: 1,
keepAlive: true,
scrollTop: 0
}
},
{
path: '/shopping',
name: 'shopping',
component: resolve => require(['@/views/shopping/index.vue'], resolve),
meta: {
title: '购物车',
index: 1,
keepAlive: true,
scrollTop: 0
}
},
{
path: '/detail',
name: 'detail',
component: resolve => require(['@/views/detail/index.vue'], resolve),
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");
$wrapper.scrollTop = 0;
},
注意,页面滚动的话,其他页面有滚动条的也会随之滚动,可以对其他页面里面处理,或者判断是否从详情页到列表页来判断是否缓存位置,如果不是,则回到顶部,但是注意路由钩子函数this的使用;
以上是 vant list组件滚动保留滚动条位置 的全部内容, 来源链接: utcz.com/p/239699.html