1. 程式人生 > >用Vue來實現音樂播放器(八):自動輪播圖啊

用Vue來實現音樂播放器(八):自動輪播圖啊

-s AR better hold ons ntp next start upd

slider.vue組件的模板部分

<template>
  <div class="slider" ref="slider">
    <div class="slider-group" ref="sliderGroup">
    //要註意slot插槽裏面的數據要先渲染出來
      <slot>
      </slot>
    </div>
    <div class="dots">
      <span class="dot" :class="{active: currentPageIndex === index }" v-for
="(item, index) in dots" :key="index"></span> </div> </div> </template>
<script>
  import {addClass} from ‘../../common/js/dom.js‘
  import BScroll from ‘better-scroll‘
  export default{
    data() {
      return {
        dots:[],
        currentPageIndex: 0
      }
    },
      props: {
        loop: {
            type: Boolean,
            
default: true }, autoPlay: { type: Boolean, default: true }, interval: { type: Number, default: 1000 }, showDot: { type: Boolean, default: true }, click: { type: Boolean,
default: true }, threshold: { type: Number, default: 0.3 }, speed: { type: Number, default: 400 } }, mounted() { this._setSliderWidth() setTimeout(() => { // 在初始化slider前初始化dot this._initDots() this._initSlider() if (this.autoPlay) { this._play() } }, 20) // 監聽窗口大小改變時間 window.addEventListener(‘resize‘, () => { if (!this.slider) { return } this._setSliderWidth(true) this.slider.refresh() }) }, methods:{ _setSliderWidth(isResize) { this.children = this.$refs.sliderGroup.children let width = 0 // slider 可見寬度 let sliderWidth = this.$refs.slider.clientWidth for (let i = 0; i < this.children.length; i++) { let child = this.children[i] // 設置每個子元素的樣式及高度 addClass(child, ‘slider-item‘) child.style.width = sliderWidth + ‘px‘ // 計算總寬度 width += sliderWidth } // 循環播放首尾各加一個,因此總寬度還要加兩倍的寬度 if (this.loop && !isResize) { width += 2 * sliderWidth } this.$refs.sliderGroup.style.width = width + ‘px‘ }, _initSlider() { this.slider = new BScroll(this.$refs.slider, { scrollX: true, scrollY: false, momentum: false, snap: { loop: this.loop, threshold: this.threshold, speed: this.speed }, bounce: false, stopPropagation: true, click: this.click });    this.slider.on("scrollEnd", this._onScrollEnd); this.slider.on("touchEnd", () => { if (this.autoPlay) { this._play(); } }); this.slider.on("beforeScrollStart", () => { if (this.autoPlay) { clearTimeout(this.timer); } }); }, _onScrollEnd() { let pageIndex = this.slider.getCurrentPage().pageX; this.currentPageIndex = pageIndex; // 第一輪1(第一張圖) 2 3 4 0(最後一張圖索引為0 因為放在了最前面) 1 2 3 4 0 if (this.autoPlay) { this._play(); } }, _initDots() { this.dots = new Array(this.children.length); }, _play() { clearTimeout(this.timer); this.timer = setTimeout(() => { this.slider.next(); }, this.interval); } }, watch: { loop() { this.update(); }, autoPlay() { this.update(); }, speed() { this.update(); }, threshold() { this.update(); } } } </script>

用Vue來實現音樂播放器(八):自動輪播圖啊