從別處搬的代碼用久了,一直不知道Vuex具體是為了干什么的,該怎么去用它。
Vuex是什么
vuex的核心是一個(gè)store(倉庫),包含著應(yīng)用中需要用到的state(狀態(tài))。-
什么情況下使用Vuex
為了在多個(gè)視圖引用同一個(gè) “變量 ” ,并且無論在哪個(gè)視圖中對(duì)這個(gè) “變量 ” 進(jìn)行修改,其他視圖中都能同步這個(gè)修改, 我們可以將這個(gè) “變量 ” 放入store的state中
-
如何使用Vuex【同步狀態(tài)state】
假如,我們需要在多個(gè)視圖中使用同一個(gè)變量 count,先在store(倉庫)中添加一個(gè)state(狀態(tài))名為 count :
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } } })如今我們想修改count的值,雖然可以直接使用 store.state.count = 5 ;但是這樣無法實(shí)現(xiàn)同步,vuex中提供了mutations方法,需要使用 state.commit('increment ') 來觸發(fā) mutations 來改變 count的值。還可以用commit方法傳參來更靈活的修改count的值:
mutaion: { increment (state, n) { state.count += n; } } store.commit('increment', 10);單單傳一個(gè)參數(shù)可能很難滿足我們開發(fā)的需求,這時(shí)可以傳入一個(gè)payload(提交載荷):
mutation: { increment (state, payload) { state.totalPrice += payload.price + payload.count; } } store.commit({ type: 'increment', price: 10, count: 8 })為了觸發(fā)所有的視圖同步更新count的功能,我們將count的值放入計(jì)算屬性 computed中:
computed: { count () { return this.$store.state.count } }使用這種方法看起來很冗余,vuex提供了mapState輔助函數(shù),我們可以通過這樣使用,以簡化編碼:
computed: mapState([ 'count' ])這樣便可以將 this.count 映射為 store.state.count;
-
Getters對(duì)象
雖然我們同步更新了這個(gè)狀態(tài),但往往會(huì)需要再對(duì)這個(gè)參數(shù)進(jìn)行處理之后才能使用,當(dāng)然,我們可以在每一處引用的地方添加一個(gè)處理函數(shù),但是,當(dāng)這個(gè)處理過程需要更改時(shí),我們需要在所有引用的地方復(fù)制一遍 新的處理函數(shù),很沒有效率,不便于維護(hù)。
Vuex中g(shù)etters對(duì)象,可以方便我們?cè)趕tore中做集中的處理。Getters接受state作為第一個(gè)參數(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) } } })組件中調(diào)用形式:
computed: { doneTodos () { return this.$store.getters.doneTodos } }同理,這樣調(diào)用比較繁瑣,vuex提供了一個(gè)和mapState 作用相同的輔助函數(shù) mapGetters,在計(jì)算屬性中這樣引入:
computed: mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) -
同步函數(shù)mutations
mutations是改變state的唯一方法,我們?cè)陧?xiàng)目中需要改變state的值時(shí),使用 state.commit('increment') ,不如直接使用methods那么方便,vuex提供了mapMutations映射函數(shù),使我們?cè)谡{(diào)用methods時(shí)可以映射為 state.commit調(diào)用:// 注 Mutations必須是同步函數(shù)。 methods: { ...mapMutations([ 'increment' // 映射 this.increment() 為 this.$store.commit('increment') ]), ...mapMutations({ add: 'increment' // 映射 this.add() 為 this.$store.commit('increment') }) } 異步函數(shù)Aciton
媽耶,看不懂,我再去學(xué)學(xué)..........