美文网首页
Vue中实现返回顶部的核心代码

Vue中实现返回顶部的核心代码

作者: 六寸光阴丶 | 来源:发表于2020-04-10 13:49 被阅读0次
    <template>
      <div v-show="isShow" @click="handleClick">
        返回顶部
      </div>
    </template>
    
    <script>
    import throttle from 'throttle-debounce/throttle'
    export default {
      name: 'SideBar',
      props: {
        visibilityHeight: {
          type: Number,
          required: false,
          default: 150
        }
      },
      data () {
        return {
          el: null,
          container: null,
          isShow: false
        }
      },
      mounted () {
        this.init()
        this.throttledScrollHandler = throttle(300, this.onScroll)
        this.container.addEventListener('scroll', this.throttledScrollHandler)
      },
      methods: {
        init () {
          this.container = document
          this.el = document.documentElement
        },
        handleClick (index) {
          this.scrollToTop()
        },
        onScroll () {
          const scrollTop = this.el.scrollTop
          this.isShow = scrollTop >= this.visibilityHeight
        },
        scrollToTop () {
          let el = this.el
          let step = 0
          let interval = setInterval(() => {
            if (el.scrollTop <= 0) {
              clearInterval(interval)
              return
            }
            step += 10
            el.scrollTop -= step
          }, 20)
        }
      }
    }
    </script>
    

    相关文章

      网友评论

          本文标题:Vue中实现返回顶部的核心代码

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