vue 页面切换的时候vuex记录之前的滚动条位置

beforeRouteEnter (to, from, next) {
    let aScrollY = store.getters.aScrollY
    setTimeout(function () {
      window.scrollTo(0, aScrollY);
    }, 0) //同步转异步操作 */
    /* 页设置了keepalive,所以直接setTimeout 0的时候就能使用,如果你的页面不是keepalive,需要等nextTick后或者setTimeout 设置足够长的时间,再执行scrollTo。 */
    next()

  },
  beforeRouteLeave (to, from, next) {//记录离开时的位置
    let position = window.scrollY
    this.$store.commit('changeaScrollY', position)
    next()

  },
import store from '../store'

如果使用了区域滚动

import Bscroll from 'better-scroll'
beforeRouteEnter (to, from, next) {
    next(vm => {
      console.log(vm)  //vm为vue的实例
      vm.$nextTick(() => {
        vm.scroll = new Bscroll(vm.$refs.qiehuan)
        let bScrollY = store.getters.bScrollY
        vm.scroll.scrollTo(0, bScrollY)
        console.log(vm.scroll.y)//y为负数
      })
    })

  },
  beforeRouteLeave (to, from, next) {//记录离开时的位置
    console.log(this.scroll.y)

    let position = this.scroll.y
    this.$store.commit('changebScrollY', position)
    next()

  }

 next(vm=>{console.log(‘next’) }) 
这个里面的代码很晚执行,执行时机在组件mounted周期之后

猜你喜欢

转载自www.cnblogs.com/sunjuncoder/p/9971922.html