vue2.0实现音乐/视频播放进度条组件

2020-06-14 06:03:31易采站长站整理

<progress-bar :percent="percent" @percentChange="setProgress"></progress-bar>
</div>
<span class="time time-r">{{formatTime(currentSong.duration)}}</span>
</div>

解释:两个span为左右两个时间值,progress-bar为调用的组件,需要传入percent值,用于子组件设置进度条长度
percent值来自于audio的currenTime与歌曲总长度的比值:


// 计算百分比
percent() {
return Math.min(1, this.currentTime / this.currentSong.duration)
}

@percentChange为子组件中派发过来的事件,详细请看子组件中源码及注释“_triggerPercent()”部分,此事件调用的方法用于接收子组件传过来的拖动按钮、点击进度条改变歌曲播放进度后的播放百分比,用于改变父组件中audio标签的currentTime,进而将歌曲播放进度设置为当前时间。

以下为父组件中,接收到子组件派发过来的事件后调用的函数。


// 设置进度
setProgress(percent) {
// 根据子组件传过来的百分比设置播放进度
this.$refs.audio.currentTime = this.currentSong.duration * percent
// 拖动后设置歌曲播放
if (!this.playing) {
this.togglePlaying()
}
},

样式(本人使用stylus):


.progress-wrapper
display flex
.time
font-size 0.24rem
&.time-l
position absolute
bottom 1.62rem
left 1rem
&.time-r
position absolute
bottom 1.62rem
right 1rem
.progress-bar-wrapper
position absolute
bottom 1.5rem
left 1.7rem
width 4.2rem

至此,进度条组件的实现及使用方法均介绍完毕。