Vue 實(shí)現(xiàn)滾動(dòng)滑塊功能

實(shí)現(xiàn)效果

image.png

ScrollProgress組件

<template>
  <div class="flex justify-center items-center w-full mb-12">
    <div ref="progress" class="w-45 h-4 bg-gray-300 rounded-2 relative">
      <div ref="progressPivot" class="h-full w-11 bg-dgray rounded-2 absolute"></div>
    </div>
  </div>
</template>
<script type="text/ecmascript-6">
  export default {
    props: {
      progress: {
        type: Number,
        default: 0
      },
      progressWidth: {
        type: Number,
        default: 45
      },
      progressHeight: {
        type: Number,
        default: 4
      },
      pivotWidth: {
        type: Number,
        default: 11
      },
    },
    watch: {
      progress(value) {
        this.$refs.progressPivot.style.left = (this.progressWidth - this.pivotWidth) * value + 'px'
      }
    },
    mounted() {
      this.$refs.progress.style.height = this.progressHeight + 'px'
      this.$refs.progress.style.width = this.progressWidth + 'px'
      this.$refs.progressPivot.style.width = this.pivotWidth + 'px'
    },
  }
</script>

使用示例

<!-- scrollView內(nèi)容 -->
<div ref="scrollView" class="overflow-x-scroll w-100">
  <div v-for="(i, index) in list" :key="index" class="text-12 w-70 mr-8">
    {{i}}
  </div>
</div>

<!--進(jìn)度條 -->
<scroll-progress :progress="progress" />
import ScrollProgress from '@/components/ScrollProgress'

components: {
 ScrollProgress
},
<!-- 監(jiān)聽(tīng)數(shù)據(jù)列表,網(wǎng)絡(luò)請(qǐng)求結(jié)束后顯示列表才能獲取到scrollView -->
watch: {
 list() {
   this.$nextTick(() => {
     let scrollView = this.$refs.scrollView;
     if (!scrollView) return
     scrollView.addEventListener("scroll", this.scroll, false);
   })
 }
},
methods: {
    scroll(e) {
       let leftViewOffset = e.target.scrollLeft;
       let contentW = e.target.scrollWidth-e.target.clientWidth
       this.progress = leftViewOffset/contentW
    },
}

使用時(shí)導(dǎo)入css樣式即可 tailwindcss

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容