需求:点击首页列表进入二级页面,返回的时候保持在原位置。
keep-alive是Vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。
1:App.vue
<template>
<div id="app">
<!--页面返回不刷新-->
<!-- // 缓存组件跳转的页面 -->
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<!-- // 非缓存组件跳转页面 -->
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
2:router / index.js
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home,
meta: {
keepAlive: true // 需要缓存
}
},{
path: '/home',
name: 'home',
component: Home,
meta: {
keepAlive: true // 需要缓存
}
},
...
]
scrollBehavior(to, from, savedPosition) { //解决拖动时多个页面互相影响的问题,当切换到新路由时,想要页面滚到顶部
// if (savedPosition) {
// return savedPosition
// } else {
// if (from.meta.keepAlive) {
// from.meta.savedPosition = document.body.scrollHeight
// }
// }
// return {
// x: 0,
// y: 0
// }
}
})
3:home.vue
3.1:定义初始滚动高度
data() {
return {
scrollY:0,
}
},
3.2:确定滚动的位置
.container {
position: absolute;
top: 0;bottom: 0;
width: 100%;
padding: 0;margin:0;
overflow: hidden;
overflow-y: scroll;
}
3.3:重点!! (不用放在methods里)
//记录离开时的位置
beforeRouteLeave (to, from, next) {
//保存滚动条元素div的scrollTop值
this.scrollY = document.querySelector('.container').scrollTop
// console.log(this.scrollY)
next()
},
// 为div元素重新设置保存的scrollTop值
beforeRouteEnter (to, from, next) {
next(vm => { // vm = this
document.querySelector('.container').scrollTop = vm.scrollY
// console.log( document.querySelector('.container').scrollTop )
})
},
by the way…一直获取不到当前滚动位置(scrollTop),可能是没有添加滚动条或者没找对。