1.在項目main.js中引入store,并掛載
import store from './store'
......
new Vue({
el: '#app',
render: h => h(App),
//把store對象提供給‘store’選項,這可以把store的實例注入所有的組件
store
})
2.建立store倉庫贱呐,結(jié)構(gòu)如下
3.state的理解
單一狀態(tài)樹
我的理解就是:state狀態(tài)就是數(shù)據(jù)源
比如很多個視圖層文件(組件)都是同一個數(shù)據(jù)來源得哆,不同視圖的操作都需要改為同一個數(shù)據(jù)源醋火。那么就可以把這個數(shù)據(jù)提出來,存在state中潜圃。
4.getters的理解
getters是對state做一些映射----基礎(chǔ)的代理
export const singer = state => state.singer
有時候我們需要從 store 中的 state 中派生出一些狀態(tài)
// 計算屬性
export const currentSong = (state) => {
return state.playlist[state.currentIndex] || {}
}
上面的currentSong就是通過playlist數(shù)據(jù)與currentIndex計算而來的
5.mapGetters輔助函數(shù)
mapGetters輔助函數(shù)缸棵,僅僅是將store中的 getters 映射到局部計算屬性:
首先在組件中引入:
import {mapGetters} from 'vuex'
其次,在計算屬性computed中使用
computed: {
// 使用對象展開運算符將 getters 混入 computed 對象中
...mapGetters([
'playing'
// 'playing'對應(yīng)getters中的playing
// 如果想給getter屬性換個名字: 'newplaying': 'playing'
])
}
6.mutation-types的理解
存儲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',對應(yīng)的是mutation-types中的字符串'SET_FULL_SCREEN'隧出,setFullScreen是新起的對應(yīng)的事件名踏志,方便在methods中使用。
9.actions的理解
mutations提交同步狀態(tài)的改變胀瞪;
actions提交異步的狀態(tài)改變针余,實際上actions是先將改變反饋到mutation,再通過mutation進行提交凄诞。
10.index.js
可以理解為入口圆雁,或者接口
總結(jié)一番:
以上截圖是我做得一個音樂APP項目中的截圖。
以播放器全屏帆谍、縮小為例:
假設(shè)處于當(dāng)前模式(如圖):
當(dāng)點擊左上角的向下箭頭圖標(biāo)的時候:
1)觸發(fā)methods中的back()函數(shù),
2)提交數(shù)據(jù)false
methods: {
back() {
this.setFullScreen(false)
},
...mapMutations({
setFullScreen: 'SET_FULL_SCREEN',
})
}
3)back()函數(shù)中的
this.setFullScreen
對應(yīng)mapMutations中的
setFullScreen: 'SET_FULL_SCREEN',
4)mapMutations中的
setFullScreen: 'SET_FULL_SCREEN',
對應(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對應(yīng)back()函數(shù)的參數(shù)false
6)通過mutations改變state的狀態(tài)
7)state.fullScreen的狀態(tài)變?yōu)閒alse,映射到getters中
export const fullScreen = state => state.fullScreen
在通過mapGetters插入到組件中
...mapGetters([
'fullScreen'
])
8)觸發(fā)
<div class="mini-player" v-show="!fullScreen" @click="open">
播放器縮小汛蝙,如下圖所示