vuex作为vue统一的数据管理组件,能够在多个组件中传递数据。vuex一般包含state,mutation,action,getters等模块。
使用时,新建store文件夹,包含index.js,actions.js,getters.js,state.js,mutations.js,mutation-types.js文件
//index.js
//index.js作为入口模块
import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
import state from './state'
import mutations from './mutations'
import createLogger from 'vuex/dist/logger'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
actions,
getters,
state,
mutations,
strict: debug,
plugins: debug ? [createLogger()] : []
})
//state.js
//包含原始数据
const state = {
singer: {},
playing: false,
fullScreen: false,
playlist: [],
sequenceList: [],
mode: playMode.sequence,
currentIndex: -1
}
export default state
//mutation-types.js
//确定有多少种mutations
export const SET_SINGER = 'SET_SINGER'
export const SET_PLAYING_STATE = 'SET_PLAYING_STATE'
export const SET_FULL_SCREEN = 'SET_FULL_SCREEN'
//mutations.js
//对store的修改
import * as types from './mutation-types'
const mutations = {
[types.SET_SEARCH_HISTORY](state, history) {
state.searchHistory = history
},
[types.SET_PLAY_HISTORY](state, history) {
state.playHistory = history
},
[types.SET_FAVORITE_LIST](state, list) {
state.favoriteList = list
}
}
export default mutations
//getters.js
//确定getters
export const singer = state => state.singer
export const playing = state => state.playing
export const fullScreen = state => state.fullScreen
//actions.js
//当一个动作中多次修改state时使用actions
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)
}
在组件中修改或者获取某一个state时,可以使用vuex提供的语法糖
-----get-----
//html中可直接使用
<div class="normal-player" v-show="fullScreen">
播放器
</div>
//mapGetters获取的数据可以直接作为computed中的属性
import {mapGetters} from 'vuex'
export default {
computed:{
...mapGetters([
'fullScreen',
'playlist'])
}
}
-----set-----
//使用mapActions语法糖,获取到的actions直接作为方法调用
selectItem(item, index) {
this.selectPlay({
list: this.songs,
index
})
},
...mapActions([
'selectPlay'
])
//使用mapMutations语法糖,和mapActions类似
...mapMutations({
setFullScreen: 'SET_FULL_SCREEN'
}),
back() {
this.setFullScreen(false)
},