基于vue2.0实现音乐/视频播放进度条组件的方法及代码解释,具体内容如下
需求分析:
①:进度条随着歌曲的播放延长,歌曲播放完时长度等于黑色总进度条长度;时间实时更新。
②:当滑动按钮时,实时更新播放时间,橙色进度条长度也会随着按钮的滑动而改变,当滑动结束时,橙色区域停留在滑动结束的位置,歌曲从当前进度开始播放。
③:点击进度条,橙色进度条长度变为点击处至起点的长度,并从当前点开始播放歌曲。

大概思路:
①:左边的时间可以通过audio播放时派发的timeupdate事件获取,右边的时间为接口获取的当前歌曲的总时间。
②:进度条子组件的长度通过父组件传入一个percent值计算,percent值为播放进度与总进度的比值。
③:进度条的滑动及点击结束后,需要向父组件传递一个percent值,使用this.$emit()像父组件派发事件,父组件中设置事件响应函数,接收percent参数值,用于改变audio中当前播放的音乐进度。
详细实现,关键代码已经注释:
先上组件源码:
<template>
<div class="progress-bar" ref="progressBar" @click="progressClick">
<div class="bar-inner">
<div class="progress" ref="progress"></div>
<div class="progress-btn-wrapper"ref="progressBtn"
@touchstart.prevent = "progressTouchStart"
@touchmove.prevent = "progressTouchMove"
@touchend = "progressTouchEnd"
>
<div class="progress-btn"></div>
</div>
</div>
</div>
</template> <script type="text/ecmascript-6">
// 进度条按钮宽度,由于style中没有设置width,因此只能用clientWidth获取
export default {
data() {
return {
btnWidth: {
type: Number,
default: 0
},
touchInfo: {
initiated: false
}
}
},
props: {
percent: {
type: Number,
default: 0
}
},
mounted() {
this.btnWidth = document.getElementsByClassName('progress-btn')[0].clientWidth
},
methods: {
// 点击按钮
progressTouchStart(e) {
// 记录touch事件已经初始化
this.touchInfo.initiated = true
// 点击位置
this.touchInfo.startX = e.touches[0].pageX
// 点击时进度条长度
this.touchInfo.left = this.$refs.progress.clientWidth
},
// 开始移动
progressTouchMove(e) {
if (!this.touchInfo.initiated) {
return
}
// 计算移动距离
const moveX = e.touches[0].pageX - this.touchInfo.startX










