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

2020-04-10  本文已影响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>
上一篇下一篇

猜你喜欢

热点阅读