vue详情页回到列表页定位到原来的位置(transform)

在滚动列表时,找到是哪个div的 transform 在变化:

列表页路由离开守卫里,通过找到滚动的 div 的 transform 值,可以得到向上滚动的距离,保存到 vuex 中

  beforeRouteLeave(to, from, next) {
    if (to.query.type !== 'details') return
    let str = getComputedStyle(
      this.$refs['scroll-wrapper'].$el.firstElementChild
    ).transform // 找到滚动的元素的 transform
    let y
    if (str !== 'none') {
      let arr = str.match(/(?<=().*(?=))/)[0].split(',')
      y = arr[arr.length - 1]
    }
    this.setScrollY(y) // 保存到vuex中
    next()
  }

列表页的created中,将获取到的scrollY值再赋给滚动的元素的style

  async created() {
    await this.getList() // 用 await 修饰后,下面的代码相当于是在 promise 的 then 方法中执行,前提是 getList 函数中返回了成功的 promise 状态(return Promise.resolve()
   this.$nextTick(() => {
      let y = this.scrollY // 从vuex中获取的
      console.log('拿到y', this.scrollY)
      this.$refs[
        'scroll-wrapper'
      ].$el.firstElementChild.style = `transform: translate(0px, ${y}px) translateZ(0px);`
    })
  }

注:这种方法,可以做到定位到原来的位置,但是从详情页回到列表页,还是请求接口了,如果要不请求接口,需要使用keep-alive

原文地址:https://www.cnblogs.com/wuqilang/p/14826018.html