vue-music关于Player播放器组件详解(2)
打开播放器的状态
import {mapGetters,mapMutations} from 'vuex';
...mapGetters([
'fullScreen',
'playList',
'currentSong',
'playing',
'currentIndex',
])
注意:不可在组件中直接赋值改版vuex 中的状态 this.fullScreen = false 需要通过mutations 改变,定义mutation-types 和mutations 然后 用vuex的 mapMutations 代理方法调用
[types.SET_FULL_SCREEN](state, flag) {
state.fullScreen = flag
},
import {mapGetters,mapMutations} from 'vuex';
methods:{
...mapMutations({
setFullScreen:"SET_FULL_SCREEN",
}),
back(){
this.setFullScreen(false)
},
}
设置点击播放按钮方法
<i :class="playIcon" @click="togglePlaying"></i>
togglePlaying(){
this.setPlayingState(!this.playing); //改变全局变量playing 的属性
},
// 然后watch 监听playing 操作实际的audio 标签的播放暂停
watch:{
playing(newPlaying){
let audio = this.$refs.audio;
this.$nextTick(() => {
newPlaying ? audio.play():audio.pause();
})
}
},
// 用计算属性改变相应的播放暂停图标
playIcon(){
return this.playing? 'icon-pause':'icon-play'
},
设置点击播放上一首和下一首按钮方法。用mapGetters 获取currentIndex 的值(加一或减一) 并改变,从而改变 currentSong 的状态,监听切换播放。判断播放列表界限重置。
prev(){
if(!this.songReady){
return;
}
let index = this.currentIndex - 1;
if(index === -1){ //判断播放列表界限重置
index = this.playList.length-1;
}
this.setCurrentIndex(index);
if(!this.playing){ //判断是否播放改变播放暂停的icon
this.togglePlaying();
}
this.songReady = false;
},
next(){
if(!this.songReady){
return;
}
let index = this.currentIndex + 1;
if(index === this.playList.length){ //判断播放列表界限重置
index = 0;
}
this.setCurrentIndex(index);
if(!this.playing){
this.togglePlaying();
}
this.songReady = false;
},
监听audio 元素标签的canpaly 事件,当歌曲加载就绪 和 error 事件,当歌曲发生错误的时候,做用户体验,防止用户快速切换导致报错。
设置songReady 标志位 如果歌曲没有准备就绪,点击下一首的时候直接return false
data(){
return {
songReady:false,
}
},
ready(){
this.songReady = true;
},
error(){
this.songReady = true;
},
进度条
audio元素监听 timeupdate 事件获取当前播放时间的 可读写属性 时间戳。用formt做格式化时间处理,(_pad 为补零函数 )
获取音频总时长 currentSong.duration
