方法1:
- 在router.js里面(即路由文件中),此时模式为 history(注意为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 }
}
}
})
- keep-alive
meta: {
title: 'home',
keepAlive: true
}
- 页面加载路由的地方
<keep-alive >
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
注意: 位置确实记录上了(加缓存,返回不刷新页面),也就是说,返回不触发created。存在修改信息的页面不会及时更新数据
方法2:scrollBehavior
- 同样为history 模式下
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { x: 0, y: 0 }
}
}
从详情页面返回 使用 history.back()
方法3:
- 在hash 模式下
// route中的data钩子, 需要在离开页面前手动保存滚动条位置
route : {
data : function () {
var _this = this;
// 返回同一个位置
var scrollTop = sessionStorage.getItem("scrollTop");
if (scrollTop) {
_this.$nextTick(function () {
$(dom).scrollTop(scrollTop);
});
}
}
}
下一个方法类似都是在离开前 保存
在进入时读取
方法4:
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)
})
}
//组件内的守卫
beforeRouteEnter (to, from, next) {
next(vm => {
// 通过 `vm` 访问组件实例
vm.$nextTick(function(){
let position = vm.$store.state.position //返回页面取出来
console.log("beforeRouteEnter moments update: ", position);
window.scroll(0, position)
// setTimeout(function(){window.scroll(0, position)},1000)
})
})
}