1.在項(xiàng)目main.js中引入store,并掛載
import store from './store'
......
new Vue({
el: '#app',
render: h => h(App),
//把store對(duì)象提供給‘store’選項(xiàng),這可以把store的實(shí)例注入所有的組件
store
})
2.建立store倉(cāng)庫(kù),結(jié)構(gòu)如下

3.state的理解
單一狀態(tài)樹(shù)
我的理解就是:state狀態(tài)就是數(shù)據(jù)源
比如很多個(gè)視圖層文件(組件)都是同一個(gè)數(shù)據(jù)來(lái)源,不同視圖的操作都需要改為同一個(gè)數(shù)據(jù)源。那么就可以把這個(gè)數(shù)據(jù)提出來(lái),存在state中。

4.getters的理解
getters是對(duì)state做一些映射----基礎(chǔ)的代理
export const singer = state => state.singer
有時(shí)候我們需要從 store 中的 state 中派生出一些狀態(tài)
// 計(jì)算屬性
export const currentSong = (state) => {
return state.playlist[state.currentIndex] || {}
}
上面的currentSong就是通過(guò)playlist數(shù)據(jù)與currentIndex計(jì)算而來(lái)的

5.mapGetters輔助函數(shù)
mapGetters輔助函數(shù),僅僅是將store中的 getters 映射到局部計(jì)算屬性:
首先在組件中引入:
import {mapGetters} from 'vuex'
其次,在計(jì)算屬性computed中使用
computed: {
// 使用對(duì)象展開(kāi)運(yùn)算符將 getters 混入 computed 對(duì)象中
...mapGetters([
'playing'
// 'playing'對(duì)應(yīng)getters中的playing
// 如果想給getter屬性換個(gè)名字: 'newplaying': 'playing'
])
}

6.mutation-types的理解
存儲(chǔ)mutation相關(guān)的狀態(tài)常量

7.mutations的理解
更改 Vuex 的 store 中的狀態(tài)的唯一方法是提交 mutation

8.mapMutations輔助函數(shù)
首先,組件中引入
import {mapMutations} from 'vuex'
其次,在methods中使用
methods: {
back() {
this.setFullScreen(false)
},
open() {
this.setFullScreen(true)
},
changeMode() {
const mode = (this.mode + 1) % 3
this.setPlayMode(mode)
let list = null
if (mode === playMode.random) {
list = shuffle(this.sequenceList)
} else {
list = this.sequenceList
}
this._resetcurrentIndex(list)
this.setPlayList(list)
},
...mapMutations({
setFullScreen: 'SET_FULL_SCREEN',
setPlayingState: 'SET_PLAYING_STATE',
setCurrentIndex: 'SET_CURRENT_INDEX',
setPlayMode: 'SET_PLAY_MODE',
setPlayList: 'SET_PLAYLIST'
})
}
我的理解:
這里的字符串 'SET_FULL_SCREEN',對(duì)應(yīng)的是mutation-types中的字符串'SET_FULL_SCREEN',setFullScreen是新起的對(duì)應(yīng)的事件名,方便在methods中使用。
9.actions的理解
mutations提交同步狀態(tài)的改變;
actions提交異步的狀態(tài)改變,實(shí)際上actions是先將改變反饋到mutation,再通過(guò)mutation進(jìn)行提交。

10.index.js
可以理解為入口,或者接口

總結(jié)一番:
以上截圖是我做得一個(gè)音樂(lè)APP項(xiàng)目中的截圖。
以播放器全屏、縮小為例:
假設(shè)處于當(dāng)前模式(如圖):

當(dāng)點(diǎn)擊左上角的向下箭頭圖標(biāo)的時(shí)候:
1)觸發(fā)methods中的back()函數(shù),
2)提交數(shù)據(jù)false
methods: {
back() {
this.setFullScreen(false)
},
...mapMutations({
setFullScreen: 'SET_FULL_SCREEN',
})
}
3)back()函數(shù)中的
this.setFullScreen
對(duì)應(yīng)mapMutations中的
setFullScreen: 'SET_FULL_SCREEN',
4)mapMutations中的
setFullScreen: 'SET_FULL_SCREEN',
對(duì)應(yīng),mutation-types中的
export const SET_FULL_SCREEN = 'SET_FULL_SCREEN'
5)再到mutations中的
[types.SET_FULL_SCREEN](state, flag) {
state.fullScreen = flag
},
其中參數(shù)flag對(duì)應(yīng)back()函數(shù)的參數(shù)false
6)通過(guò)mutations改變state的狀態(tài)
7)state.fullScreen的狀態(tài)變?yōu)閒alse,映射到getters中
export const fullScreen = state => state.fullScreen
在通過(guò)mapGetters插入到組件中
...mapGetters([
'fullScreen'
])
8)觸發(fā)
<div class="mini-player" v-show="!fullScreen" @click="open">
播放器縮小,如下圖所示
