vuex進階知識點鞏固
我們先回憶一下上一篇的程式碼
computed:{
getName(){
return this.$store.state.name
}
}
這裡假設現在邏輯有變,我們最終期望得到的資料(getName),是基於 this.$store.state.name 上經過複雜計算得來的,剛好這個getName要在好多個地方使用,那麼我們就得複製好幾份.
vuex 給我們提供了 getter,請看程式碼 (檔案位置 /src/store/index.js)
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ // 類似 vue 的 data state: { name: 'oldName' }, // 類似 vue 的 computed -----------------以下5行為新增 getters:{ getReverseName: state => { return state.name.split('').reverse().join('') } }, // 類似 vue 裡的 mothods(同步方法) mutations: { updateName (state) { state.name = 'newName' } } })
然後我們可以這樣用 檔案位置 /src/main.js
computed:{
getName(){
return this.$store.getters.getReverseName
}
}
事實上, getter 不止單單起到封裝的作用,它還跟vue的computed屬性一樣,會快取結果資料, 只有當依賴改變的時候,才要重新計算.
二、 actions和$dispatch
細心的你,一定發現我之前程式碼裡 mutations 頭上的註釋了 類似 vue 裡的 mothods(同步方法)
為什麼要在 methods 後面備註是同步方法呢? mutation只能是同步的函式,只能是同步的函式,只能是同步的函式!! 請看vuex的解釋:
現在想象,我們正在 debug 一個 app 並且觀察 devtool 中的 mutation 日誌。每一條 mutation 被記錄, devtools 都需要捕捉到前一狀態和後一狀態的快照。然而,在上面的例子中 mutation 中的非同步函式中的回撥讓這不 可能完成:因為當 mutation 觸發的時候,回撥函式還沒有被呼叫,devtools 不知道什麼時候回撥函式實際上被調 用——實質上任何在回撥函式中進行的狀態的改變都是不可追蹤的。
那麼如果我們想觸發一個非同步的操作呢? 答案是: action + $dispatch, 我們繼續修改store/index.js下面的程式碼
檔案位置 /src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
export default new Vuex.Store({
// 類似 vue 的 data
state: {
name: 'oldName'
},
// 類似 vue 的 computed
getters:{
getReverseName: state => {
return state.name.split('').reverse().join('')
}
},
// 類似 vue 裡的 mothods(同步方法)
mutations: {
updateName (state) {
state.name = 'newName'
}
},
// 類似 vue 裡的 mothods(非同步方法) -------- 以下7行為新增
actions: {
updateNameAsync ({ commit }) {
setTimeout(() => {
commit('updateName')
}, 1000)
}
}
})
然後我們可以再我們的vue頁面裡面這樣使用
methods: {
rename () {
this.$store.dispatch('updateNameAsync')
}
}
三、 Module 模組化
當專案越來越大的時候,單個 store 檔案,肯定不是我們想要的, 所以就有了模組化. 假設 src/store 目錄下有這2個檔案
moduleA.js
export default {
state: { ... },
getters: { ... },
mutations: { ... },
actions: { ... }
}
moduleB.js
export default {
state: { ... },
getters: { ... },
mutations: { ... },
actions: { ... }
}
那麼我們可以把 index.js 改成這樣
import moduleA from './moduleA'
import moduleB from './moduleB'
export default new Vuex.Store({
modules: {
moduleA,
moduleB
}
})
這樣我們就可以很輕鬆的把一個store拆分成多個.
四、 總結
•actions 的引數是 store 物件,而 getters 和 mutations 的引數是 state .
•actions 和 mutations 還可以傳第二個引數,具體看vuex官方文件
•getters/mutations/actions 都有對應的map,如: mapGetters , 具體看vuex官方文件
•模組內部如果怕有命名衝突的話,可以使用名稱空間, 具體看vuex官方文件
•vuex 其實跟 vue 非常像,有data(state),methods(mutations,actions),computed(getters),還能模組化.