歌手详情页如下所示,在单击歌曲时,需要显示播放器(包括歌词显示、专辑封面、切换歌曲、歌曲列表、切换播放模式等等)。本篇主要讲解如何在歌手详情页点击歌曲时,如何控制播放器的显示。
由于在多个页面都能点击歌曲显示播放器,因此使用vuex对播放器进行状态管理。
state数据:
playing: false, // 播放器是否正在播放
fullScreen: false, // 播放器属于全屏状态还是缩小状态
playlist: [],// 播放列表
sequenceList: [],// 顺序列表
mode: playMode.sequence,// 播放模式:顺序、循环、随机
currentIndex: -1// 当前播放歌曲的索引
其中sequceList为正常的歌曲列表,playlist为当前播放的列表,当顺序播放是,sequenceList和playlist相同
getters:
export const playing = state => state.playing
export const fullScreen = state => state.fullScreen
export const playlist = state => state.playlist
export const sequenceList = state => state.sequenceList
export const mode = state => state.mode
export const currentIndex = state => state.currentIndex
export const currentSong = state => {
return state.playlist[currentIndex] || {}
}
mutation-types:
export const SET_PLAYING_STATE = 'SET_PLAYING'
export const SET_FULL_SCREEN = 'SET_FULL_SCREEN'
export const SET_PLAYLIST = 'SET_PLAYLIST'
export const SET_SEQUENCE_LIST = 'SET_SEQUENCE_LIST'
export const SET_PLAY_MODE = 'SET_PLAY_MODE'
export const SET_CURRENT_INDEX = 'SET_CURRENT_INDEX'
mutations:
[types.SET_PLAYING_STATE] (state, flag) {
state.playing = flag
},
[types.SET_FULL_SCREEN] (state, flag) {
state.fullScreen = flag
},
[types.SET_PLAYLIST] (state, list) {
state.playlist = list
},
[types.SET_SEQUENCE_LIST] (state, list) {
state.sequenceList = list
},
[types.SET_PLAY_MODE] (state, mode) {
state.mode = mode
},
[types.SET_CURRENT_INDEX] (state, index) {
state.currentIndex = index
}
歌曲列表使用的song-list组件开发,因此在song-list组件中监听click事件来感知是否需要打开播放器。
由于song-list是一个基础组件,不要在组件内写事件的具体执行逻辑,只需要将事件派发出去就行。
methods中的selectItem方法:
selectItem(song, index) {
this.$emit('select', song, index)
}
事件派发出去之后在music-list组件中可以监听到是否执行点击操作:
<song-list @select="selectItem" :songs="songs"></song-list>
本来应该在music-list组件中的selectItem事件中提交mutation,由于提交的mutation包含SET_PLAY_STATE、SET_FULL_SCREEN、SET_PLAYLIST等等多个操作,因此我们对提交多个mutation使用actions进行一次封装,actions代码如下:
import * as types from './mutation-types'
export const selectPlay = function ({state, commit}, {list, index}) {
commit(types.SET_PLAYLIST, list)
commit(types.SET_SEQUENCE_LIST, list)
commit(types.SET_CURRENT_INDEX, index)
commit(types.SET_FULL_SCREEN, true)
commit(types.SET_PLAYING_STATE, true)
}
这时,我们可以在music-list中使用mapActions将actions中的selectPlay函数映射到music-list组件methods对象中,然后在selectItem函数中调用selectPlay就可以提交多个mutation了:
selectItem(song, index) {
this.selectPlay({
list: this.songs,
index
})
},
...mapActions([
'selectPlay'
])
网友评论