vue 详情页返回列表页面时保持列表的位置状态不变

方法一:

1.在router.js里面(即路由文件中),此时模式为 history

const router = new VueRouter({
mode: 'history',
routes,
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
if (from.meta.keepAlive) {
from.meta.savedPosition = document.body.scrollTop
}
return { x: 0, y: to.meta.savedPosition || 0 }
}
}
})
2.在router.js里面需要记录位置的单页面里面
let routes = [
{
path: '/',
name: 'home',
component: home,
meta: {
title: 'home',
keepAlive: true
}
}
3.App.vue里面<div ></router-view>
4.位置确实记录上了(加缓存,返回不刷新页面),弊端就是返回不触发created,所以有些页面需要返回触发的东西都写在activated里面。

方法二:

beforeRouteLeave(to, from, next){
let position = window.scrollY()
this.$store.commit('SAVE_POSITION', position) //离开路由时把位置存起来
next()
}
在页面中取值

updated () {
this.$nextTick(function(){
let position = this.$store.state.position //返回页面取出来
window.scroll(0, position)
})
}
用updated 或者 beforeUpdate 钩子都可以 代码都写在要保存滑动距离的界面
方法三:用默认的hash模式的

一个list页点击进入detail页,我在这时记录下list页滚动条的位置,然后在detail页返回到list页时设置滚动条位置为刚才保存那个值。


// list页route中的data钩子
route : {
data : function () {
var _this = this;
// 返回同一个位置
var scrollTop = sessionStorage.getItem("scrollTop");
if (scrollTop) {
_this.$nextTick(function () {
$(".abuild-record-layout").scrollTop(scrollTop);
});
}
}
}
$nextTick将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。它跟全局方法 Vue.nextTick 一样,不同的是回调的 this 自动绑定到调用它的实例上。

方法四:scrollBehavior方法

1.router文件中设置为 mode: 'history', 模式

2.router设置

scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }

原文链接:https://blog.csdn.net/qq_40963664/article/details/79850589