state.js
与组件、项目、模块相关的底层数据
const state = {
singer: {},
playing: false,
fullScreen: false,
playlist: [],
sequenceList: [],
mode: playMode.sequence,
currentIndex:-1
}
export default state
getters.js
对数据的映射,可以写一些复杂的判断逻辑
export const singer = state => state.singer
export const playing = state => state.playing
export const currentSong = (state) => {
return state.playlist[state.currentIndex] || {}
}
mutations.js
定义对数据修改的逻辑
const mutations = {
[types.SET_SINGER](state, singer){
state.singer = singer
},
[types.SET_PLAYING_STATE](state, flag) {
state.playing = flag
},
[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
},
}
export default mutations
mutation-types.js
使用常量替代 mutation 事件类型
export const SET_SINGER = 'SET_SINGER'
export const SET_PLAYING_STATE = 'SET_PLAYING_STATE'
export const SET_PLAYLIST = 'SET_PLAYLIST'
export const SET_SEQUENCE_LIST = 'SET_SEQUENCE_LIST'
export const SET_CURRENT_INDEX = 'SET_CURRENT_INDEX'
action.js
import * as types from './mutation-types'
export const selectPlay = function ({commit, state}, {list, index}) {
commit(types.SET_SEQUENCE_LIST, list)
commit(types.SET_PLAYLIST, list)
commit(types.SET_CURRENT_INDEX, index)
commit(types.SET_FULL_SCREEN, true)
commit(types.SET_PLAYING_STATE, true)
}
调用action
import {mapActions} from 'vuex'
selectItem(item, index){
this.selectPlay({
list:this.songs,
index
})
},
...mapActions([
'selectPlay'
])
mapGetters和mapMutations
import {mapGetters,mapMutations} from 'vuex'
export default {
computed: {
...mapGetters([
'fullScreen',
'playlist',
'currentSong'
])
},
methods: {
back(){
this.setFullScreen(false)
},
open(){
this.setFullScreen(true)
},
...mapMutations({
setFullScreen: 'SET_FULL_SCREEN'
})
}
}