[Vue 生態] Vuex 文檔閱讀筆記

1. 最簡單的 Store

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.state 來獲取狀態對象, 以及通過store.commit 來觸發狀態的變更。

store.commit('increment')
console.log(store.state.count) // 1

但是,現在無法在其他組件上訪問到狀態對象。 爲了達到這一目的,我們需要將store和Vue 實例關聯起來。

在main.js 中

// 引入store 後
new Vue({
    el:'#app',
    store:store,
})

這樣,從所有子組件中,都可以這樣去修改和訪問state狀態對象中的值:

methods:{
    increment(){
        this.$store.commit('increment')
        console.log(this.$store.state.count)
    }
}

⭐ 我們修改狀態對象中的值,並不是直接去修改, 而是通過提交 mutation 。

這樣做的目的,是代碼閱讀更加易於理解,且易於調試。

另外, 由於store 中的狀態是響應式的,在組件中調用store 中的狀態,僅需要在計算屬性中去返回即可。 觸發 變化也僅僅實在組件的methods 中提交 mutation 。

2. 核心概念

2.1 State

2.1.1 在Vue 組件中獲得Vuex 狀態

Vuex 的狀態存儲時響應式的,從store 實例中讀取狀態的最簡單方法就是在計算屬性中 返回某個狀態:

const Counter  = {
    template : `<div>{{ count }}</div>`,
    computed: {
        count () {
            return this.$store.state.count
        }
    }
}

2.1.2 mapState 輔助函數

當一個組件需要獲取多個狀態 , 每一個狀態都上上面那樣去定義computed 有一些繁瑣, vue 爲了簡化這個過程,給我們提供了 mapState 輔助函數。

import { mapState } from 'vuex'

export default{
    //...
    computed: mapState({
        count: state=> state.count,
        countAlias : 'count'
    })
}

當計算屬性中的屬性名和state 中的子節點相同時,可以直接將名稱字符串作爲一個字符串數組元素, 然後將這個字符串數組傳入mapState

computed:mapState([
    'count'
])
//即, this.count 的映射爲 store.state.count

2.1.3 對象展開運算符

mapState 函數返回的是一個對象, 怎麼將它與局部計算屬性混合使用呢 ?

computed:{
    localComputed(){/*...*/},
    ...mapState({
        //...
    })
}

2.2 Getters

有時候,我們需要從 store 中的 state 中派生出一些狀態,例如對列表進行過濾並計數:

computed: {
    doneTodosCount (){
        return this.$store.state.todos.filter(todo => todo.done).length
    }
}

如果,有多個組件需要用到此屬性,我們要麼複製這個函數,或者抽取到一個共享函數,然後再多出導入它 —— 無論哪種方式都不是很理想。

Vuex 允許它們在 store 中定義getter (可以認爲是store的計算屬性。) 就像計算屬性一樣,getter 的返回值會根據它的依賴被緩存起來,其只有當它的依賴值發送了改變纔會被重新計算

Getter 接收 state 作爲其第一個參數 :

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)
        }
    }
})

2.2.1 通過屬性訪問

Getter 會暴露爲 store.getters 對象, 你可以以屬性的形式訪問這些值:

store.getters.doneTodos // [{ id: 1, text: '...', done: true }]

Getter 也可以接收其他getter作爲第二個參數:

getter:{
    //...
    doneTodosCount: (state,getters) => {
        return getters.doneTodos.length
    }
}
store.getters.doneTodosCount // -1

我們可以很容易地在任何組件中使用它:

computed: {
    dontTodosCount (){
        return this.$store.getter.doneTodosCount
    }
}

注意, getter 在通過屬性訪問時是作爲Vue 的響應式系統的一部分緩存其中的

2.2.2 通過方法訪問

你也可以通過讓getter 返回一個函數,來實現給getter 傳參。 在你對 store 裏的數組進行查詢時會非常有用。

getters: {
    //...
    getTodoById: (state) => (id) => {
        return state.todos.find(todo => todo.id === id)
    }
}

⭐以上代碼等同於

getters;{
    //...
    getTodoById: function(state){
        return function(id){
            return state.todos.find(todo => todo.id === id)
        }
    }
}
store.getters.getTodoById(2);// { id:2, text: '...', done: false }

⚠️ 這裏的調用很奇怪,這個state 形參是怎麼回事?

這裏涉及到 “函數的柯里化”, 簡單的說:

//①
const add = (x, y) => x + y;
add(2,3) // 5

這段代碼的柯里化將會是:

//②
const add = x => y => x + y;

其es5代碼爲:

const add = function(x){
    return function(y){
        return x + y
    }
}

因此:

getters: {
    //...
    getTodoById: (state) => (id) => {
        return state.todos.find(todo => todo.id === id)
    }
}

就可以寫成其等同式(就像② 和 ①是等同的):

getters: {
    //...
    getTodoById: (state,id) => {
        return state.todos.find(todo => todo.id === id)
    }
}

而 state 這個參數是getters 的默認傳參,因此,可以這樣去調用:

store.getters.getTodoById(2);

理解參考自:

https://stackoverflow.com/a/32787782/11375753
https://stackoverflow.com/a/67221323/12261182

注意: getter 在通過方法訪問時, 每次都會去進行調用, 而不會緩存結果。

2.2.3 mapGetters 輔助函數

mapGetters 輔助函數僅僅是將 store 中的getter 映射到局部計算屬性:

import { mapGetters } from 'vuex'

export default {
    //...
    computed:{
        // 使用對用展開運算符將getter 混入 computed 對象中
        ...mapGetters({
            'doneTodosCount',
            'anotherGetter',
            //...
        })
    }
}

如果你想將一個 getter 屬性另取一個名字, 使用對象形式:

...mapGetters({
    // 把 `this.doneCount` 映射爲 `this.$store.getters.doneTodosCount`
    doneCount: 'doneTodosCount'
})

2.3 Mutation

要更改 Vuex 的 store 中的狀態的唯一方法是提交 mutation 。Vuex 中的mutation非常類似於事件 : 每個 mutation 都有一個字符串的 事件類型(type) 和一個 回調函數(handler)。 這個回調函數就是我們實際進行狀態更改的地方,並且它會接受 state 作爲第一個參數:

const store = new Vuex.store({
    state: {
        count: 1
    },
    mutations: {
        increment (state){
            // 變更狀態
            state.count ++ 
        }
    }
})

你不能直接調用一個 mutation handler 。 這個選項更像是事件註冊 : “當觸發一個類型(type)爲 increment 的 mutation 時, 調用此函數。 " 要喚醒一個 mutation handler , 你需要以相應的 type 調用 store.commit 方法:

store.commit('increment')

2.3.1 提交載荷(Payload)

你可以向 store.commit 傳入額外的參數, 即 mutation的 載荷(payload):

//...
mutations: {
    increment (state, n){
        state.count += n
    }
}
store.commit('increment',10)

在大多數情況下, 載荷(Payload) 應該是一個對象, 這樣可以包含多個字段並且記錄的 mutation 會更易讀:

//...
mutations:{
    increment(state, payload){
        state.count += payload.amount
    }
}
store.commit('increment',{
    amount:10
})

2.3.2 對象風格的提交方式

提交一個mutation 的另一種方式是直接使用包含 type屬性的對象 :

store.commit({
    type: 'increment',
    amount: 10
})

當使用對象風格的提交方式, 整個對象都作爲載荷傳給 mutation函數, 因此 handler 保持不變 :

mutations:{
    increment (state, payload){
        state.count += payload.amount
    }
}

2.3.3 Mutations 需遵守 Vue 的響應規則

既然Vuex 的 store 中的狀態是響應式的,那麼當我們變更狀態時, 監視狀態的Vue 組件也會自動更新。這也意味着Vuex 中的mutation 也需要與使用Vue 一樣遵守一些注意事項。

  1. 最好提前在你的 store 中初始化好所有屬性

  2. 當需要在對象上添加新屬性時, 你應該

    • 使用 Vue.set(obj, 'newProp', 123) , 或者

    • 以新對象替換老對象。 例如, 利用 對象展開運算符 , 我們可以這樣寫:

      state.obj = { ...state.obj, newProp: 123 }
      

2.3.4 使用常量替代 Mutation 事件類型

使用常量替代 mutation 事件類型在各種 Flux 實現中是很常見的模式。 這樣可以使得 linter 之類的工具發揮作用, 同時把這些常量放在單獨的文件中可以讓你的代碼合作者對整個 app 包含的mutation 一目瞭然

// mutation-types.js

export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'

const store = new Vuex.store({
    state: {/*...*/},
    mutations:{
        // 我們可以使用 ES2015 風格的計算屬性命名功能來使用一個常量作爲函數名
        [SOME_MUTATION](state){
            // mutate state
        }
    }        
})

2.3.5 Mutation 必須是同步函數

一天重要的原則就是要記住 mutation 必須是同步函數

2.3.6 在組件中提交 Mutation

你可以在組件中使用 this.$store.commit('xxx') 提交 mutation, 或者使用 mapMutations 輔助函數將組件中的 methods 映射爲 store.commit 調用 (需要在根節點注入 store)。

import { mapMutations } from 'vuex'

export default {
    //...
    methods:{
        ...mapMutations([
            'increment', // 將 `this.increment() ` 映射爲 `this.$store.commit('increment')`
            
            //`mapMutations` 也支持載荷(Payload):
			'incrementBy'// 將 `this.incrementBy(amount)` 映射爲 `this.$store.commit('incrementBy', amount)`
        ]),
        ...mapMutations({
            add:'increment' // alias, 將 `this.add()` 映射爲 `this.$store.commit('increment')`
        })
    }
}

2.4 Action

Action 類似於 mutation , 不同在於 :

  • Action 提交的是 mutation , 而不是直接變更狀態。
  • Action 可以包含任意異步操作。

一個簡單的 action

const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment (state) {
            state.count++
        }
    },
    actions:{
        increment (context){
            context.commit('increment')
        }
    }
})

Action 函數接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調用 context.commit 提交一個 mutation,或者通過 context.statecontext.getters 來獲取 state 和 getters。當我們在之後介紹到 Modules 時,你就知道 context 對象爲什麼不是 store 實例本身了。

實踐中, 我們經常會用到 ES2015 的參數解構 來簡化代碼

actions :{
    increment({ commit }){
        commit('increment')
    }
}

2.4.1 分發 Action

Action 通過 store.dispatch 方法觸發:

store.dispatch('increment')

乍一眼看上去感覺多此一舉,我們直接分發 mutation 豈不更方便?實際上並非如此,還記得 mutation 必須同步執行這個限制麼?Action 就不受約束!我們可以在 action 內部執行異步操作:

actions: {
    incrementAsync({ commit }){
        setTimeout(()=>{
            commit('increment')
        },1000)
    }
}

Actions 支持 同樣的載荷方式和對象方式進行分發 :

// 以載荷形式分發
store.dispatch('incrementAsync',{
    amount: 10
})

// 以對象形式分發
store.dispatch({
    type:'incrementAsync',
    amount: 10
})

2.4.2 在組件中分發 Action

你在組件中使用this.$store.dispatch('xxx') 分發 action, 或者使用 mapActions 輔助函數將組件的 methods 映射爲 store.dispatch 調用

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' // alias 將`this.add()` 映射爲 `this.$store.dispatch('increment')`
        })
    }
}

2.4.3 組合 Action

Action 通常是異步的, 那麼如何知道 action 什麼時候結束呢 ? 更重要的是, 我們如何才能組合多個 action, 以處理更加複雜的異步流程 ?

首先,你需要明白, store.dispatch 可以處理被觸發的 action 的處理函數返回的 Promise, 並且store.dispatch 仍舊返回 Promise :

actions: {
    actionA({ commit }){
        return new Promise((resolve, reject)=>{
            setTimeout(()=>{
                commit('someMutation')
                resolve()
            },1000)
        })
    }
}

現在你可以 :

store.dispatch('actionA').then(() => {
    //...
})

在另外一個 acion 中也可以:

actions : {
    //...
    actionB({ dispatch, commit }){
        return dispatch('actionA').then(() => {
            commit('someOtherMutation')
        })
    }
}

最後,如果我們利用 async / await , 我們可以如下組合 action:

// 假設 getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

一個 store.dispatch 在不同模塊中可以觸發多個 action 函數。在這種情況下,只有當所有觸發函數完成後,返回的 Promise 纔會執行。

2.5 Module

由於使用單一狀態樹,應用的所有狀態會集中到一個比較大的對象。當應用變得非常複雜時,store 對象就有可能變得相當臃腫。

爲了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的狀態
store.state.b // -> moduleB 的狀態

2.5.1 模塊的局部狀態

對於模塊內部的 mutation 和 getter,接收的第一個參數是模塊的局部狀態對象

const moduleA = {
  state: () => ({
    count: 0
  }),
  mutations: {
    increment (state) {
      // 這裏的 `state` 對象是模塊的局部狀態
      state.count++
    }
  },

  getters: {
    doubleCount (state) {
      return state.count * 2
    }
  }
}

同樣,對於模塊內部的 action,局部狀態通過 context.state 暴露出來,根節點狀態則爲 context.rootState

const moduleA = {
  // ...
  actions: {
    incrementIfOddOnRootSum ({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }
}

對於模塊內部的 getter,根節點狀態會作爲第三個參數暴露出來:

const moduleA = {
  // ...
  getters: {
    sumWithRootCount (state, getters, rootState) {
      return state.count + rootState.count
    }
  }
}

2.5.2 命令空間

默認情況下,模塊內部的 action、mutation 和 getter 是註冊在全局命名空間的——這樣使得多個模塊能夠對同一 mutation 或 action 作出響應。

如果希望你的模塊具有更高的封裝度和複用性,你可以通過添加 namespaced: true 的方式使其成爲帶命名空間的模塊。當模塊被註冊後,它的所有 getter、action 及 mutation 都會自動根據模塊註冊的路徑調整命名。例如:

const store = new Vuex.Store({
  modules: {
    account: {
      namespaced: true,

      // 模塊內容(module assets)
      state: () => ({ ... }), // 模塊內的狀態已經是嵌套的了,使用 `namespaced` 屬性不會對其產生影響
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },

      // 嵌套模塊
      modules: {
        // 繼承父模塊的命名空間
        myPage: {
          state: () => ({ ... }),
          getters: {
            profile () { ... } // -> getters['account/profile']
          }
        },

        // 進一步嵌套命名空間
        posts: {
          namespaced: true,

          state: () => ({ ... }),
          getters: {
            popular () { ... } // -> getters['account/posts/popular']
          }
        }
      }
    }
  }
})

啓用了命名空間的 getter 和 action 會收到局部化的 getterdispatchcommit。換言之,你在使用模塊內容(module assets)時不需要在同一模塊內額外添加空間名前綴。更改 namespaced 屬性後不需要修改模塊內的代碼。

2.5.2.1 在帶命名空間的模塊內訪問全局內容(Global Assets)

如果你希望使用全局 state 和 getter,rootStaterootGetters 會作爲第三和第四參數傳入 getter,也會通過 context 對象的屬性傳入 action。

若需要在全局命名空間內分發 action 或提交 mutation,將 { root: true } 作爲第三參數傳給 dispatchcommit 即可。

modules: {
  foo: {
    namespaced: true,

    getters: {
      // 在這個模塊的 getter 中,`getters` 被局部化了
      // 你可以使用 getter 的第四個參數來調用 `rootGetters`
      someGetter (state, getters, rootState, rootGetters) {
        getters.someOtherGetter // -> 'foo/someOtherGetter'
        rootGetters.someOtherGetter // -> 'someOtherGetter'
      },
      someOtherGetter: state => { ... }
    },

    actions: {
      // 在這個模塊中, dispatch 和 commit 也被局部化了
      // 他們可以接受 `root` 屬性以訪問根 dispatch 或 commit
      someAction ({ dispatch, commit, getters, rootGetters }) {
        getters.someGetter // -> 'foo/someGetter'
        rootGetters.someGetter // -> 'someGetter'

        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

        commit('someMutation') // -> 'foo/someMutation'
        commit('someMutation', null, { root: true }) // -> 'someMutation'
      },
      someOtherAction (ctx, payload) { ... }
    }
  }
}
2.5.2.2 在帶命名空間的模塊註冊全局 action

若需要在帶命名空間的模塊註冊全局 action,你可添加 root: true,並將這個 action 的定義放在函數 handler 中。例如:

{
  actions: {
    someOtherAction ({dispatch}) {
      dispatch('someAction')
    }
  },
  modules: {
    foo: {
      namespaced: true,

      actions: {
        someAction: {
          root: true,
          handler (namespacedContext, payload) { ... } // -> 'someAction'
        }
      }
    }
  }
}
2.5.2.3 帶命名空間的綁定函數

當使用 mapState, mapGetters, mapActionsmapMutations 這些函數來綁定帶命名空間的模塊時,寫起來可能比較繁瑣:

computed: {
  ...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  })
},
methods: {
  ...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    'some/nested/module/bar' // -> this['some/nested/module/bar']()
  ])
}

對於這種情況,你可以將模塊的空間名稱字符串作爲第一個參數傳遞給上述函數,這樣所有綁定都會自動將該模塊作爲上下文。於是上面的例子可以簡化爲:

computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  })
},
methods: {
  ...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
  ])
}

而且,你可以通過使用 createNamespacedHelpers 創建基於某個命名空間輔助函數。它返回一個對象,對象裏有新的綁定在給定命名空間值上的組件綁定輔助函數:

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'
    ])
  }
}
2.5.2.4 給插件開發者的注意事項

如果你開發的插件(Plugin)提供了模塊並允許用戶將其添加到 Vuex store,可能需要考慮模塊的空間名稱問題。對於這種情況,你可以通過插件的參數對象來允許用戶指定空間名稱:

// 通過插件的參數對象得到空間名稱
// 然後返回 Vuex 插件函數
export function createPlugin (options = {}) {
  return function (store) {
    // 把空間名字添加到插件模塊的類型(type)中去
    const namespace = options.namespace || ''
    store.dispatch(namespace + 'pluginAction')
  }
}

2.5.3 模塊動態註冊

在 store 創建之後,你可以使用 store.registerModule 方法註冊模塊:

import Vuex from 'vuex'

const store = new Vuex.Store({ /* 選項 */ })

// 註冊模塊 `myModule`
store.registerModule('myModule', {
  // ...
})
// 註冊嵌套模塊 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
  // ...
})

之後就可以通過 store.state.myModulestore.state.nested.myModule 訪問模塊的狀態。

模塊動態註冊功能使得其他 Vue 插件可以通過在 store 中附加新模塊的方式來使用 Vuex 管理狀態。例如,vuex-router-sync (opens new window)插件就是通過動態註冊模塊將 vue-router 和 vuex 結合在一起,實現應用的路由狀態管理。

你也可以使用 store.unregisterModule(moduleName) 來動態卸載模塊。注意,你不能使用此方法卸載靜態模塊(即創建 store 時聲明的模塊)。

注意,你可以通過 store.hasModule(moduleName) 方法檢查該模塊是否已經被註冊到 store。

2.5.4 保留 state

在註冊一個新 module 時,你很有可能想保留過去的 state,例如從一個服務端渲染的應用保留 state。你可以通過 preserveState 選項將其歸檔:store.registerModule('a', module, { preserveState: true })

當你設置 preserveState: true 時,該模塊會被註冊,action、mutation 和 getter 會被添加到 store 中,但是 state 不會。這裏假設 store 的 state 已經包含了這個 module 的 state 並且你不希望將其覆寫。

2.5.5 模塊重用

有時我們可能需要創建一個模塊的多個實例,例如:

如果我們使用一個純對象來聲明模塊的狀態,那麼這個狀態對象會通過引用被共享,導致狀態對象被修改時 store 或模塊間數據互相污染的問題。

實際上這和 Vue 組件內的 data 是同樣的問題。因此解決辦法也是相同的——使用一個函數來聲明模塊狀態(僅 2.3.0+ 支持):

const MyReusableModule = {
  state: () => ({
    foo: 'bar'
  }),
  // mutation, action 和 getter 等等...
}

3.進階

項目結構

Vuex 並不限制你的代碼結構。但是,它規定了一些需要遵守的規則:

  1. 應用層級的狀態應該集中到單個 store 對象中。
  2. 提交 mutation 是更改狀態的唯一方法,並且這個過程是同步的。
  3. 異步邏輯都應該封裝到 action 裏面。

只要你遵守以上規則,如何組織代碼隨你便。如果你的 store 文件太大,只需將 action、mutation 和 getter 分割到單獨的文件。

對於大型應用,我們會希望把 Vuex 相關代碼分割到模塊中。下面是項目結構示例:

├── index.html
├── main.js
├── api
│   └── ... # 抽取出API請求
├── components
│   ├── App.vue
│   └── ...
└── store
    ├── index.js          # 我們組裝模塊並導出 store 的地方
    ├── actions.js        # 根級別的 action
    ├── mutations.js      # 根級別的 mutation
    └── modules
        ├── cart.js       # 購物車模塊
        └── products.js   # 產品模塊

請參考購物車示例 (opens new window)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章