Vue Implementation Returns Top Button Instance Code

  • 2021-08-31 07:17:10
  • OfStack

Preface

This article mainly introduces the Vue implementation return to the top button method, the following words do not say much, to look at the code directly

Example code:


<template>
 <div class="scrollTop">
 <div class="backTop"
   @click="backTop">
  <button v-show="flag_scroll">
      Back to the top 
  </button>
  </div>
  // Data source 
  <div></div>
 </div>
</template> 
<script>
export default {
 name: 'scrollTop',
 data() {
 return {
 
  flag_scroll: false,
  scroll: 0,
 }
 },
 computed: {},
 methods: {
 // Returns the top event 
 backTop() {
  document.getElementsByClassName('scrollTop')[0].scrollTop = 0
 },
 // Sliding over 200 Display buttons when 
 handleScroll() {
  let scrollTop = document.getElementsByClassName('scrollTop')[0]
  .scrollTop
  console.log(scrollTop)
  if (scrollTop > 200) {
  this.flag_scroll = true
  } else {
  this.flag_scroll = false
  }
 },
 },
 mounted() {
 window.addEventListener('scroll', this.handleScroll, true)
 },
 created() { },
}
</script>

<style scoped>
.scrollTop{
 width: 100%;
 height: 100vh;
 overflow-y: scroll;
}
.backTop {
 position: fixed;
 bottom: 50px;
 z-index: 100;
 right: 0;
 background: white;
}
</style>

Summarize


Related articles: