播放器能夠經過歌手詳情列表,歌單的詳情列表,排行榜甚至是搜索結果去打開,即多個組件均可以操做這個播放器,當這個播放器一旦打開之後,縮小播放器,它仍然能夠在後臺播放運行。因此控制播放器的數據必定是全局的,那麼就須要經過vuex來管理這些數據。vue
在state.js裏 vuex須要管理如下數據:vuex
const state = { singer: {}, // 播放狀態默認爲暫停 playing: false, // 播放器默認爲收起 fullScreen: false, // 播放列表 playlist: [], // 順序列表 sequenceList: [], // 播放模式默認爲順序播放 mode: playMode.sequence, // 當前播放索引 currentIndex: -1, };
因爲播放器的播放模式直接用0 1 2表示會使語義化不強,因此在common=>js文件夾下新建config.jsdom
export const playMode = { sequence: 0, loop: 1, random: 2, };
有了當前播放索引currentIndex後,currentSong是能夠經過playlist和currentIndex計算而來的:currentSong = playlist [currentIndex]oop
接着在getters.js裏對這些數據進行代理:spa
export const playing = (state) => state.playing; export const fullScreen = (state) => state.fullScreen; export const playlist = (state) => state.playing; export const sequenceList = (state) => state.sequenceList; export const mode = (state) => state.mode; export const currentIndex = (state) => state.currentIndex;
getters除了能夠作簡單的代理以外呢,還能夠擔任計算屬性的角色。currentSong不須要設在state裏面,可是組件仍是須要直接訪問它。咱們能夠經過getters計算currentSong代理
export const currentSong = (state) => { return state.playlist[state.currentIndex] || {}; };
在寫mutations.js以前,一樣先在mutation-types.js定義全部事件類型code
export const SET_PLAYING_STATE = 'SET_PLAYING_STATE'; 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.js中引入mutation-types做關聯,並可對state進行修改blog
[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; },