Vuex 的學(xué)習(xí)記錄
- 資料參考網(wǎng)址
- Vuex的簡介
- Vuex 是一個類似 Redux 的狀態(tài)管理器,專為 Vue.js 應(yīng)用程序開發(fā)预吆,采用集中式存儲管理應(yīng)用的所有組件的狀態(tài)倘感,并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化施敢,并集成到了Vue的官方調(diào)試工具 devtools extension
- Vuex的使用情況: 當開發(fā)大型單頁面應(yīng)用(SPA)時,會出現(xiàn)多個視圖組件依賴同一個狀態(tài),來自不同視圖的行為需要變更同一個狀態(tài)。
- 基礎(chǔ)使用及API說明
-
常用api及基礎(chǔ)寫法
// func 指代 Function室囊,函數(shù) const store = new Vuex.Store( { state: {} | func, // 根state對象藻雪,初始數(shù)據(jù)或狀態(tài)賦值 mutations: {}, // 純函數(shù)修改數(shù)據(jù)的方法秘噪,處理函數(shù)總是接受 state 作為第一個,payload 作為第二個參數(shù)(可選) actions: {}, // 事件勉耀,動作指煎, 處理函數(shù)總是接受 context 作為第一個參數(shù)蹋偏,payload 作為第二個參數(shù)(可選)。 getters: {}, // store 的計算屬性至壤,返回值會根據(jù)它的依賴被緩存起來威始,且只有當它的依賴值發(fā)生改變才會被重新計算 modules: {}, // 包含子模塊的對象,會被合并到 store plugins: [], // 包含應(yīng)用在store上的插件方法像街,這些插件接受store作為唯一參數(shù)黎棠,可以監(jiān)聽 mutation(用于外部地數(shù)據(jù)持久化、記錄或調(diào)試)或者提交 mutation(用于內(nèi)部數(shù)據(jù)镰绎,例如 websocket 或 某些觀察者) strict: Boolean, // 默認值:false, 使Vuex store進入嚴格模式脓斩,任何 mutation 處理函數(shù)以外修改 Vuex state 都會拋出錯誤。 } );
-
最簡單的 Vuex 示例
``` import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } } }); store.commit('increment'); console.log(store.state.count) // 1 ``` 注明:每一個Vuex應(yīng)用就是一個store,在store中包含組件的共享狀態(tài) `state` 和改變狀態(tài)的方法 `mutations`畴栖,且只能通過 `mutations` 改變store的 `state` 的狀態(tài)俭厚,不能通過類似 `store.state.count = 5` 的方式直接更改(直接修改,狀態(tài)不會被同步驶臊,組件也不會重新渲染)
-
在Vue組件使用Vuex
- 在<b>根組件</b>挪挤,將store 注入到每一個子組件中,在子組件就可以通過
this.$store
訪問:
// 根組件 import store from './store'; new Vue({ el: '#app', router, store, render: h => h(App) }) // Counter 組件 export default { name: 'counter', computed: { count () { return this.$store.state.count } } }
- <b>Getters</b>: Vuex 中
getters
對象关翎,接受state作為第一個參數(shù)扛门,可以方便我們在 store 對 state 進行處理計算。Getter也可以接受其他 <b>getters</b> 作為第二參數(shù)
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } }) // 在Vue中通過 store.getters對象調(diào)用 computed: { doneTodos () { return this.$store.getters.doneTodos } } // Getter也可以接受其他getters作為第二個參數(shù) getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) }, doneTodosCount: (state, getters) => { return getters.doneTodos.length } }
- <b>Mutations</b>: 每一個mutation都有一個事件類型type和一個回調(diào)函數(shù)handler纵寝,
Mutations
必須是同步函數(shù)论寨,若需要異步操作,就需要Actions
了爽茴。
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { state.count++; // 變更state狀態(tài) } } }) // 調(diào)用mutation葬凳,需要通過store.commit方法調(diào)用mutation type store.commit('increment'); // 可以向store.commit傳入第二參數(shù),也就是mutation的payload(多數(shù)情況傳對象) mutaion: { increment (state, n) { state.count += n; }, outcrement (state, payload) { state.totalPrice += payload.price + payload.count; } } store.commit('increment', 10); store.commit('outcrement', { price: 10, count: 8 });
- 在<b>根組件</b>挪挤,將store 注入到每一個子組件中,在子組件就可以通過
-
-
- Vuex.Store 組件綁定的輔助函數(shù)
-
mapState(namespace?: string, map: Array<string> | Object), 第一個參數(shù)可選室奏。當一個組件需要獲取多個狀態(tài)的時候火焰,將這些狀態(tài)都聲明為計算屬性會有些重復(fù)和冗余。使用
mapState
輔助函數(shù)可以幫助我們批量生成計算屬性胧沫。// 在單獨構(gòu)建的版本中輔助函數(shù)為 Vuex.mapState import { mapState } from 'vuex' export default { computed: mapState({ // 箭頭函數(shù)可使代碼更簡練 count: state => state.count, // 不使用mapState輔助函數(shù)的寫法 // 傳字符串參數(shù) 'count' 等同于 `state => state.count` countAlias: 'count', // 寫法一昌简,使用別名方式 // 為了能夠使用 `this` 獲取局部狀態(tài),必須使用常規(guī)函數(shù) countPlusLocalState (state) { return state.count + this.localCount // 寫法二绒怨,常規(guī)函數(shù)方式 } // }) } // 當映射的計算屬性的名稱與state的子節(jié)點名稱相同時纯赎,可用字符串數(shù)組的寫法 export default { computed: mapState(['count']) // 映射 this.count 為 store.state.count } // 使用 ES6 的 對象展開運算符 的寫法去簡化 export default { computed: { ...mapState(['count','total']) } }
- mapGetters(namespace?: string, map: Array<string> | Object) : 將 store 中的 getter 映射到局部計算屬性。
import { mapGetters } from 'vuex' export default { computed: { // 使用對象展開運算符將 getter 混入 computed 對象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter' ]) } } // 想將getter屬性另取一個名字南蹂,需使用對象形式 export default { computed: { mapGetters({ doneCount: 'doneTodosCount' // 映射 `this.doneCount` 為`store.getters.doneTodosCount` }) } }
- mapActions(namespace?: string, map: Array<string> | Object): 將組件的 methods 映射為 store.dispatch 調(diào)用
import { mapActions } from 'vuex' export default { methods: { ...mapActions([ 'increment', // 將 `this.increment()` 映射為 `this.$store.dispatch('increment')` // `mapActions` 也支持載荷: 'incrementBy' // 將 `this.incrementBy(amount)` 映射為 `this.$store.dispatch('incrementBy', amount)` ]), ...mapActions({ add: 'increment' // 將 `this.add()` 映射為 `this.$store.dispatch('increment')` }) } }
- mapMutations(namespace?: string, map: Array<string> | Object): 將組件中的 methods 映射為 store.commit 調(diào)用
import { mapMutations } from 'vuex' export default { methods: { ...mapMutions([ 'increment', // 將`this.increment()` 映射為 'this.$store.commit('increment')' // `mapMutations` 也支持載荷: 'incrementBy' // 將 `this.incrementBy(amount)` 映射為 `this.$store.commit('incrementBy', amount)` ]), ...mapMutations({ add: 'increment', // 將 `this.add()`映射為`this.$store.commit('increment')` }) } }
-
createNamespacedHelpers(namespace: string): 建基于某個命名空間輔助函數(shù)
import { createNamespacedHelpers } from 'vuex' const { mapState, mapActions } = createNamespacedHelpers('some/nested/module') export default { computed: { // 在 `some/nested/module` 中查找 ...mapState({ a: state => state.a, b: state => state.b }) }, methods: { // 在 `some/nested/module` 中查找 ...mapActions([ 'foo', 'bar' ]) } }
-
- Vuex.Store 的實例屬性
store.commit( '', { } ) : 提交 mutation
store.dispatch( '', { } ) : 分發(fā) actions
store.replaceState(newstate): 替換 store 的根狀態(tài)犬金,僅用狀態(tài)合并或時光調(diào)試。
store.watch( getter, cb ) : 響應(yīng)式地監(jiān)測一個 getter 方法的返回值,當值改變時調(diào)用回調(diào)函數(shù)晚顷。
-
store.subscribe(Function): 注冊監(jiān)聽 store 的 mutations , Function 會在每個 mutations 完成后調(diào)用峰伙,接受 mutation 和 經(jīng)過 mutation 后的狀態(tài)作為參數(shù):
store.subscribe((mutation, state) => { console.log(mutation.type) console.log(mutation.payload) })
-
store.subscribeAction(handler: Function): 訂閱 store 的action, handler 會在分發(fā)的時候調(diào)用并接收 action 描述和當前的 store 的 state兩個參數(shù)。
store.subscribeAction((action, state) => { console.log(action.type) console.log(action.payload) })