Vue项目返回页面保持上次滚动状态方式
作者:trabecula_hj
这篇文章主要介绍了Vue项目返回页面保持上次滚动状态方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Vue项目返回页面保持上次滚动状态
使用背景:
- 首页-water-collection 当前页/列表页-water-collection-list
- 当从列表页跳转详情页面后再返回列表页面需要保持在上次滚动状态
- 每次从首页进入列表后都要滚动到顶部
一、设置列表页keepAlive缓存
{
path: '/water-collection/list',
name: 'water-collection-list',
component: () =>
import('@/views/water-collection/water-list.vue'),
meta: { title: '概要情况',keepAlive:true }
}二、第一次进入列表页面时在mounted生命周期中监听滚动事件
// mounted
this.$nextTick(() => {
this.tableScorll = this.$refs.tableScorll;
this.tableScorll.addEventListener("scroll", this.handleScroll);
});// 滚动事件,记录滚动位置并赋值给scrollTop
handleScroll() {
this.scrollTop = this.tableScorll.scrollTop;
},三、第二次之后进入在activated生命周期中监听滚动事件
// activated
this.$nextTick(() => {
this.tableScorll = this.$refs.tableScorll;
this.tableScorll.addEventListener("scroll", this.handleScroll);
});四、beforeRouteEnter判断是进入页面还是返回页面
1. 路由判断
beforeRouteEnter(to, from, next) {
next((vm) => {
if (from.name === "water-collection") {
vm.isBack = false;
} else {
vm.isBack = true;
}
});
},2. 返回页面滚动到上次位置,进入页面则滚动到顶部位置
// activated
if (this.isBack) {
if (this.scrollTop > 0) {
this.tableScorll.scrollTo(0, this.scrollTop);
}
} else {
this.scrollTop = 0;
this.tableScorll&&this.tableScorll.scrollTo(0, 0);
}3. 离开页面清除滚动事件监听
deactivated() {
this.tableScorll.removeEventListener("scroll", this.handleScroll);
},总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
