1. 程式人生 > >vuex--基礎總結

vuex--基礎總結

共享狀態,構建一箇中大型單頁應用,您很可能會考慮如何更好地在元件外部管理狀態,Vuex 將會成為自然而然的選擇

核心:store

核心概念:

state  :唯一資料來源

Getter  :從 store 中的 state 中派生出一些狀態,有多個元件需要用到此屬性,像計算屬性一樣,getter 的返回值會根據它的依賴被快取起來,且只有當它的依賴值發生了改變才會被重新計算,

Mutation   :更改 Vuex 的 store 中的狀態的唯一方法是提交 mutation;注意是同步操作

Action  :Action 提交的是 mutation,而不是直接變更狀態;Action 可以包含任意非同步操作

Module:每個模組擁有自己的 state、mutation、action、getter、甚至是巢狀子模組

專案結構:

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

建立一個store:

// 如果在模組化構建系統中,請確保在開頭呼叫了 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

在vue元件獲取狀態:

// 建立一個 Counter 元件
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return store.state.count
    }
  }
}

這種模式導致元件依賴全域性狀態單例,以下是模組化構建

Vuex 通過 store 選項,提供了一種機制將狀態從根元件“注入”到每一個子元件中(需呼叫 Vue.use(Vuex)):

const app = new Vue({
  el: '#app',
  // 把 store 物件提供給 “store” 選項,這可以把 store 的例項注入所有的子元件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})

通過在根例項中註冊 store 選項,該 store 例項會注入到根元件下的所有子元件中,且子元件能通過 this.$store 訪問到。讓我們更新下 Counter 的實現:

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

一個元件獲取多個狀態時,使用mapState()

// 在單獨構建的版本中輔助函式為 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭頭函式可使程式碼更簡練
    count: state => state.count,

    // 傳字串引數 'count' 等同於 `state => state.count`
    countAlias: 'count',

    // 為了能夠使用 `this` 獲取區域性狀態,必須使用常規函式
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}

當對映的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給 mapState 傳一個字串陣列。

computed: mapState([
  // 對映 this.count 為 store.state.count
  'count'
])

 

mapState 函式返回的是一個物件。我們如何將它與區域性計算屬性混合使用呢?通常,我們需要使用一個工具函式將多個物件合併為一個,以使我們可以將最終物件傳給 computed 屬性。但是自從有了物件展開運算子(現處於 ECMASCript 提案 stage-4 階段),我們可以極大地簡化寫法:

computed: {
  localComputed () { /* ... */ },
  // 使用物件展開運算子將此物件混入到外部物件中
  ...mapState({
    // ...
  })
}

 

Getter()

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

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

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

通過store.getters物件訪問 

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

 

Getter 也可以接受其他 getter 作為第二個引數:

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

 在元件中訪問:(計算屬性訪問 是有快取的;通過方法訪問)

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

 getter 在通過屬性訪問時是作為 Vue 的響應式系統的一部分快取其中的

通過方法訪問:

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

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

注意,getter 在通過方法訪問時,每次都會去進行呼叫,而不會快取結果。

mapGetters 輔助函式僅僅是將 store 中的 getter 對映到區域性計算屬性:

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用物件展開運算子將 getter 混入 computed 物件中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

 Mutation

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

 提交載荷(Payload)

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

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

在大多數情況下,載荷應該是一個物件,這樣可以包含多個欄位並且記錄的 mutation 會更易讀:

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

 

物件風格的提交方式

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

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

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

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

mutions遵循vue的規則:

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

當需要在物件上新增新屬性時,應該這樣做:

    1.使用 Vue.set(obj, 'newProp', 123)

  2.以新物件替換老物件  

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

大型專案建議利用常量 代替Mutions的型別,同時把這些常量放在單獨的檔案中可以讓你的程式碼合作者對整個 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
    }
  }
})

在元件中提交mutation :

 1.在元件中使用 this.$store.commit('xxx') 提交 mutation  

 2.

使用 mapMutations 輔助函式將元件中的 methods 對映為 store.commit 呼叫(需要在根節點注入 store):

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      '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')`
    })
  }
}

mutations是同步函式,不能處理非同步,需要處理非同步,則使用action提交mutations

Action: 

  • 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.state 和 context.getters 來獲取 state 和 getters。

呼叫commit多次時候,使用解構賦值:

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

 

Action 通過 store.dispatch 方法觸發:

store.dispatch('increment')

 

我們可以在 action 內部執行非同步操作:

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

 

Actions 支援同樣的載荷方式和物件方式進行分發:

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

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

在元件中分發Action:

1.元件中使用 this.$store.dispatch('xxx') 分發 action

2.使用 mapActions 輔助函式將元件的 methods 對映為 store.dispatch 呼叫(需要先在根節點注入 store):

 

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

 組合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(() => {
  // ...
})

在另外一個 action 中也可以:

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 才會執行。

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 的狀態

#模組的區域性狀態

對於模組內部的 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
    }
  }
}

名稱空間

如果希望你的模組具有更高的封裝度和複用性,你可以通過新增 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 會收到區域性化的 getterdispatch 和 commit。換言之,你在使用模組內容(module assets)時不需要在同一模組內額外新增空間名字首。更改 namespaced 屬性後不需要修改模組內的程式碼。

#在帶名稱空間的模組內訪問全域性內容(Global Assets)

如果你希望使用全域性 state 和 getter,rootState 和 rootGetter 會作為第三和第四引數傳入 getter,也會通過 context 物件的屬性傳入 action。

若需要在全域性名稱空間內分發 action 或提交 mutation,將 { root: true } 作為第三引數傳給 dispatch 或 commit 即可。

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

#在帶名稱空間的模組註冊全域性 action

若需要在帶名稱空間的模組註冊全域性 action,你可新增 root: true,並將這個 action 的定義放在函式 handler 中。例如:

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

      actions: {
        someAction: {
          root: true,
          handler (namespacedContext, payload) { ... } // -> 'someAction'
        }
      }
    }
  }
}

#帶名稱空間的繫結函式

當使用 mapStatemapGettersmapActions 和 mapMutations 這些函式來繫結帶名稱空間的模組時,寫起來可能比較繁瑣:

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

 

給外掛開發者的注意事項

如果你開發的外掛(Plugin)提供了模組並允許使用者將其新增到 Vuex store,可能需要考慮模組的空間名稱問題。對於這種情況,你可以通過外掛的引數物件來允許使用者指定空間名稱:

// 通過外掛的引數物件得到空間名稱
// 然後返回 Vuex 外掛函式
export function createPlugin (options = {}) {
  return function (store) {
    // 把空間名字新增到外掛模組的型別(type)中去
    const namespace = options.namespace || ''
    store.dispatch(namespace + 'pluginAction')
  }
}

 

模組動態註冊

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

// 註冊模組 `myModule`
store.registerModule('myModule', {
  // ...
})
// 註冊巢狀模組 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
  // ...
})

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

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

你也可以使用 store.unregisterModule(moduleName) 來動態解除安裝模組。注意,你不能使用此方法解除安裝靜態模組(即建立 store 時宣告的模組)。

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

#模組重用

有時我們可能需要建立一個模組的多個例項,例如:

如果我們使用一個純物件來宣告模組的狀態,那麼這個狀態物件會通過引用被共享,導致狀態物件被修改時 store 或模組間資料互相汙染的問題。

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

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