簡體   English   中英

如何在Vuejs中的模態作品上制作滾動條?

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

我有一個帶有進度條的模式,應該在滾動條上顯示進度。

當我第一次打開它時,它不起作用,只有當我再次關閉並再次打開模態時,它才起作用。 如何在第一時間解決此問題? 我嘗試了不同的生命周期掛鈎,但是沒有一個起作用。

<template>
 <div ref="progressbar"> .....</div>
</template>

<script>
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)
      }
   }
}


 created() {
    this.$refs.progressbar.addEventListener('scroll', this.chceckScrollBar )
  },
  beforeDestroy () {
    this.$refs.progressbar.removeEventListener('scroll',this.chceckScrollBar )
  }
</script>

您將需要將事件監聽器放入已掛載的方法中,因為ref在創建的引用中尚不存在

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

是的,您應該使用mounted方法添加滾動事件偵聽器。 Codepen上的示例 但是問題在於添加js事件偵聽器並不是一種可行的方法 您需要在元素v-on:scroll="chceckScrollBar"使用v-on:scroll="chceckScrollBar" 為什么? 當用戶滾動元素時,始終會調用on:scroll

模板

<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'
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM