[Vuejs]-How can I make scrollbar on modal works in Vuejs?

0👍

You will need to put your eventlistener into the mounted method, as the ref does not exist in the created yet

mounted() {
    this.$refs.progressbar.addEventListener('scroll', this.chceckScrollBar )
}

0👍

Yes, you should use mounted method to add scroll event listener. Example on codepen. But the problem is adding the js event listener is not a vue way. You need to use v-on:scroll="chceckScrollBar" on your element. Why? on:scroll always be called when the user scrolling the element.

template

<div id="app-vue">
   <template>
     {{percentage}}
     <div class="modal" ref="progressbar"> Hello 
       <br>
         ....
       <br></div>
  </template> 
</div>

Css

.modal {
  width:200px;
  max-height:300px;
  overflow-y: scroll;
  background-color:green;
}

Vue

let vm = new Vue({
  data() {
    return {
      percentage:0,
    };
  },
  methods: {
   chceckScrollBar () {
      const element = this.$refs.progressbar
      const clientHeight = element.clientHeight
      const scrollHeight = element.scrollHeight
      const scrollTop = element.scrollTop
      const res = (scrollTop / (scrollHeight - clientHeight)) * 100
      if (scrollHeight <= clientHeight) {
        this.percentage = 100
      } else {
        this.percentage = res.toFixed(2)
      }
   }
},

 mounted() {
    this.$refs.progressbar.addEventListener('scroll', this.chceckScrollBar );
  },
  beforeDestroy () {
    this.$refs.progressbar.removeEventListener('scroll',this.chceckScrollBar );
  },
  el: '#app-vue'
})

Leave a comment