美文网首页
vant list 配合keep-alive后,详情返回到原来位

vant list 配合keep-alive后,详情返回到原来位

作者: cooqi | 来源:发表于2020-10-21 16:30 被阅读0次

    写了一个mixins,需要用的地方引入即可

    export const handleScroll = {
      data () {
        return {
          scroll: ''
        }
      },
      mounted () {
        this.$nextTick(() => {
    //获取滚动区域dom,监听滚动事件
          this.box = document.querySelector('.s-box')
          this.box.addEventListener('scroll', this.handleScroll)
        })
      },
      methods: {
        handleScroll () {
          this.scroll = this.box && this.box.scrollTop
          // console.log(1, this.scroll)
        }
      },
      activated () {
        if (!this.$route.meta.toKeepAlive) {
          // 获取滚动列表数据,尽量统一方法,如果不同意,单独把这一块代码放入对应文件
          this.getList()
        }
        // 一定要重置toKeepAlive为true,避免一直请求数据
        this.$route.meta.toKeepAlive = true
    
        if (this.scroll > 0) {
          this.box.scrollTo(0, this.scroll)
          this.scroll = 0
          this.box.addEventListener('scroll', this.handleScroll)
        }
      },
      deactivated () {
        this.box.removeEventListener('scroll', this.handleScroll)
      },
      beforeRouteLeave (to, from, next) {
        // 离开组件的时候,
        // 如果要去的页面是回来时需要保持数据和滚动位置的,则不控制,
        // 否则重置scroll
        //backKeepAlive是定义在要往list跳转的路由上
        if (!to.meta.backKeepAlive) {
          this.box.scrollTo(1, this.scroll)
          this.scroll = 1// 此处不能是0;
        }
        next()
      },
      beforeRouteEnter (to, from, next) {
        // 进入组件前
        // 如果过来(from)的组件是不需要当前(to)组件缓存数据和位置,设置toKeepAlive为false
        if (!from.meta.backKeepAlive) {
          //toKeepAlive 不需要单独在router上定义
          to.meta.toKeepAlive = false
        }
        next()
      }
    
    }
    
    

    相关文章

      网友评论

          本文标题:vant list 配合keep-alive后,详情返回到原来位

          本文链接:https://www.haomeiwen.com/subject/myremktx.html