Vue 回到顶部

滑动区域:

<-- 内容 !-->

参数设置

scrollTop: 0,
timer: null,

思路:添加滚动监听,获取实时位置,点击返回顶部按钮时开启定时器,在定时器里处理位置

    mounted () {
       document.getElementById('target').addEventListener('scroll', this.scrollToTop)
    },
    methods: {
      scrollToTop() {
        this.scrollTop = document.getElementById('target').scrollTop
      },
      backTop() {
        this.timer = setInterval(()=>{
          this.scrollToTopTimer()
        },20)
      },
      scrollToTopTimer() {
        let scrollTop = this.scrollTop
        if(scrollTop > 0) {
          scrollTop -= 100
          if(scrollTop <= 0) {
            scrollTop = 0
            clearInterval(this.timer)
          }
        }
        document.getElementById('target').scrollTop = scrollTop
      }
    },
    destroyed () {
      clearInterval(this.timer)
      document.getElementById('target').removeEventListener('scroll', this.scrollToTop)
    }

监听与定时器要销毁

你可能感兴趣的:(Vue 回到顶部)