如何在vue中实现一个定时自动间隔多少秒滚动的滚动条?

作者站长头像
站长
· 阅读数 17

如何在vue中实现一个定时自动间隔多少秒滚动的滚动条?

mounted () {
    this.getTableScroll()
  },
  destroyed () {
    this.getTableScroll()
  },
  methods: {
    getTableScroll () {
      if (!this.intervalID) {
        this.intervalID = setInterval(this.autoScroll, 2000)
      }
    },
    autoScroll () {
      const dom = this.$refs.scrollTable
      dom.scrollTop = dom.scrollHeight
    }

这么写能一下子滚动,不能间隔滚动,怎么优化实现呢??

参考楼里大佬答案,但是不实现已打开页面就自动间隔滚动,反而是要手动滚动并一下子回到顶部,这是哪里有问题(350是容器的固定高度)

data () {
    return {
      activeCls: 'red',
      labelCls: 'label',
      valueCls: 'value',
      // 定时器标识符
      intervalID: null,
      scrollStep: 30,
      currentScrollTop: 0
      // table_col: 'table_col'
    }
  },
  mounted () {
    this.getTableScroll()
  },
  destroyed () {
    this.clearScrollInterval()
  },
  methods: {
    getTableScroll () {
      if (!this.intervalID) {
        this.intervalID = setInterval(this.autoScroll, 2000)
      }
    },
    clearScrollInterval () {
      if (this.intervalID) {
        clearInterval(this.intervalID)
        this.intervalID = null
      }
    },
    autoScroll () {
      const dom = this.$refs.scrollTable
      this.currentScrollTop += this.scrollStep
      if (this.currentScrollTop >= dom.scrollHeight - 350) {
        this.currentScrollTop = dom.scrollHeight - 350
      }
      dom.scrollTop = dom.currentScrollTop
    }
  }
回复
1个回答
avatar
test
2024-06-30
data () {
  return {
    activeCls: 'red',
    labelCls: 'label',
    valueCls: 'value',
    // 定时器标识符
    intervalID: null,
    scrollStep: 30,
    currentScrollTop: 0
    // table_col: 'table_col'
  }
},
mounted () {
  this.getTableScroll()
},
beforeDestroy () {
  this.clearScrollInterval()
},
methods: {
  getTableScroll () {
    if (!this.intervalID) {
      this.intervalID = setInterval(this.autoScroll, 2000)
    }
  },
  clearScrollInterval () {
    if (this.intervalID) {
      clearInterval(this.intervalID)
      this.intervalID = null
    }
  },
  autoScroll () {
    const dom = this.$refs.scrollTable
    this.currentScrollTop += this.scrollStep
    if (this.currentScrollTop >= dom.scrollHeight - 350) {
      this.currentScrollTop = 0 // 重置为0,重新开始滚动
    }
    dom.scrollTop = this.currentScrollTop
  }
}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容