Vue路由页面之间滚动位置互相影响

背景:A页面滚动到800位置,跳转到B页面,此时B页面也是800位置(如果B页面不够高,那么就是在底部).
A页面:keepalive是true
B页面:keepalive是false

情况1: B页面位置不动--返回--A页面仍然在800位置.
情况2: B页面滚动到顶部--返回--A页面也会回到顶部.

我想让他们的页面滚动位置各自独立...求助下各种前辈.

阅读 4.9k
3 个回答

设置路由的meta信息,控制路由的滚动行为,配合scrollBehavior方法,使每次打开新的路由页面都默认在最顶部。

const routes = [
  { path: '/', name:'index', component: index, meta: {x: 0, y: 0} },
  { path: '/swipe', name:'swipe', component: swipe, meta: {x: 0, y: 0} }
]
export default new VueRouter({
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    return to.meta;
  }
})

基于设置的路由的元信息meta,在首页index组件中设置方法记住滚动的位置保存到路由meta中:

 mounted() {
    window.onscroll = this.justifyPos;
  },
  methods: {
    justifyPos() {
      // 节流;
      if (this.timerId) {
        clearTimeout(this.timerId);
      }
      this.timerId = setTimeout(() => {
        // 滚动停止的时候记录当前组件的滚动位置信息,并且存储到对应组件的路由 meta 这个对象中
        this.$route.meta.y = window.pageYOffset;
      }, 300);
     }
 }

参考https://www.jianshu.com/p/c80...

考虑用css控制滚动呢
父元素设置

height:100%;
overflow:hidden;

滚动元素加:

overflow-y:scroll;
-webkit-overflow-scrolling:touch;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题