單一狀態樹(用一個對象就包含了所有的應用層級狀態),相似於 vue 中的 data
let store = new Vuex.Store({ state: { count: 0 } })
最簡單的是在計算屬性中返回某個狀態,這樣每當 store.state 發生變化時,能從新求取計算屬性,並觸發更新相關聯的 DOM。vue
computed: { count () { return this.$store.state.count } }
利用 mapState 輔助函數生成多個計算屬性,利用對象展開運算符將 mapState 返回的對象和局部計算屬性混合使用。
若同名,能夠給 mapState 傳一個字符串數組。vuex
import { mapState } from 'vuex' export default { //... computed: { otherComputed () { // 其餘局部計算屬性 ... }, ...mapState({ countNumber: 'count', // 等於 'countNumber: state => state.count' }) } }
能夠從 state 中派生出一些狀態,相似於 vue 中的計算屬性
接受 state 做爲第一個參數,能夠接受其餘 getter 做爲第二個參數,getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變纔會被從新計算。數組
const store = new Vuex.Store({ state: { todos: [ { id: 1, done: true }, { id: 2, done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) }, doneTodosCount: (state, getters) => { return getters.doneTodos.length } } })
// 經過屬性訪問 this.$store.getters.xxx // 經過方法訪問,getter 須要返回一個函數 this.$store.getters.xxx(xx)
import { mapGetters } from 'vuex' export default { computed: { ...mapGetters([ 'doneTodosCount', 'anotherGetter' ]) } }
更改 state 的惟一方式,必須是同步函數
相似 Mutation,但 Action 提交的是 mutation,不能直接改變 state,能夠包含異步操做。
Action 函數接受一個 context 對象,該對象與 store 實例具備相同的方法和屬性(但不是 store 實例自己),所以能夠經過 context.commit 提交一個 mutation,或經過 context.state 和 context.getters 來獲取 state 和 getters。
能夠經過 ES6 的參數解構來簡化代碼。緩存
actions: { // context 對象, obj 爲載荷(其餘參數) action1 (context, obj) { console.log(context) context.commit('xxx') }, // 參數解構 context 對象 action2 ({commit, state, getters}, obj) { console.log(commit, state, getters) } }
// 以載荷形式分發 this.$store.dispatch('updateNumber',{ number: 10 }) // 以對象形式分發 this.$store.dispatch({ type: 'updateNumber', number: 10 })