• There will be some very long documents in the project, turning to the bottom and then manually turning up is very troublesome, this article briefly records the native back to the top method, currently component libraries have their own back to the top component, much more convenient than the native method.

  • You can put ICONS, images, and so on in HTML.

< div class = "top" @ click = "toTop" v - if = "showArrow" > Sunday afternoon < / div >Copy the code
  • Setting showArrow to false in data controls display until a certain height is reached, which is not displayed without an HTML element.
data() {
  return {
    showArrow: false
  };
 },
Copy the code
  • The two lifecycle hook functions are not detailed, addEventListener() is used to add an event handler and removeEventListener() is used to remove the event handler. They all take three arguments: addEventListener(” event name “, “event handler”, “Boolean “); The third argument can be omitted and defaults to false. Event handlers added via addEventListener() can only be removed using removeEventListener();
mounted () {
  window.addEventListener('scroll', this.scrollToTop)
},
destroyed () {
  window.removeEventListener('scroll', this.scrollToTop)
},
Copy the code
  • Js method
methods: {// Click the arrow to return to the top method, ToTop () {const that = this let timer = setInterval(() => {let ispeed = math.floor (- that.scrolltop / 5) document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed if (that.scrollTop === 0) { ClearInterval (timer)}}, 16)}, Less than 60 are hidden scrollToTop () {const that = this let scrollTop = window. PageYOffset | | document. The documentElement. The scrollTop | | document.body.scrollTop that.scrollTop = scrollTop if (that.scrollTop > 60) { that.showArrow = true } else { that.showArrow = false } } },Copy the code
  • CSS styles
<style scoped>
    .top {
      position: fixed;
      display: inline-block;
      width: 50px;
      bottom: 1rem;
      right: 1rem;
      font-size: 30px;
      border-radius: 50%;
      border: 1px solid #ccc;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background: #fff;
    }
</style>
Copy the code