<template>
  <van-icon name="upgrade" class="toTop" v-show="toTopShow" @click="backTop" />
</template>

<script>
export default {
  data() {
    return {
      toTopShow: false
    };
  },
  methods: {
    handleScroll() {
      //id scroller-box是自己在组件上添加的，为了方便获取dom
      this.scrollTop = document.getElementById("app").children[0].scrollTop;
      if (this.scrollTop > 300) {
        this.toTopShow = true;
      } else {
        this.toTopShow = false;
      }
    },
    backTop() {
      // console.log(document.getElementById("app").children[0].scrollTop);
      let timer = null,
        _that = this;
      //动画，使用requestAnimationFrame代替setInterval
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        if (_that.scrollTop > 0) {
          _that.scrollTop -= 50;
          //然后修改这里实现动画滚动效果
          document.getElementById(
            "app"
          ).children[0].scrollTop = document.documentElement.scrollTop =
            _that.scrollTop;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
          _that.toTopShow = false;
        }
      });
    }
  },
  mounted() {
    //$nextTick 避免dom未加载
    this.$nextTick(function() {
      let targetScroll = document.getElementById("app").children[0];
      targetScroll.addEventListener("scroll", this.handleScroll);
    });
  },
  destroyed() {
    let targetScroll = document.getElementById("app").children[0];
    targetScroll.removeEventListener("scroll", this.handleScroll);
  }
};
</script>


<style lang="scss" scoped>
.toTop {
  position: fixed;
  right: 1.25rem;
  bottom: 1.25rem;
  font-size: 1.875rem;
  z-index: 999;
}
</style>
