安裝
npm install vuex --save
創建Store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
}
const getters ={
}
const mutations = {
}
const actions = {
}
const store = Vuex.Store({
state,
getters,
mutations,
actions,
})
由於 store 中的狀態是響應式的,在組件中調用 store 中的狀態簡單到僅需要在計算屬性中返回即可。觸發變化也僅僅是在組件的 methods 中提交 mutation
- State
由於 Vuex 的狀態存儲是響應式的,從 store 實例中讀取狀態最簡單的方法就是在計算屬性中返回某個狀態
當一個組件需要獲取多個狀態時候,將這些狀態都聲明爲計算屬性會有些重複和冗餘。爲了解決這個問題,我們可以使用 mapState 輔助函數幫助我們生成計算屬性
computed: {
localComputed () { /* ... */ },
// 使用對象展開運算符將此對象混入到外部對象中
...mapState({
// ...
})
}
- Getter
Vuex 允許我們在 store 中定義“getter”(可以認爲是 store 的計算屬性)。就像計算屬性一樣,getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變纔會被重新計算.
Getter 接受 state 作爲其第一個參數
Getter 也可以接受其他 getter 作爲第二個參數
Getter 會暴露爲 store.getters 對象,可以以屬性的形式訪問這些值
你也可以通過讓 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',
// ...
])
}
}
- Mutations
tore.commit 傳入額外的參數,即 mutation 的 載荷(payload)
mutation的第一個參數是state,第二個參數是commit傳的參數,如果是多個參數的話,載荷就是一個包含所有參數的對象
// 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 必須是同步函數
可以在組件中使用 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` 也支持載荷:
'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 將 `this.add()` 映射爲 `this.$store.commit('increment')`
})
}
}
- Action
Action 提交的是 mutation,而不是直接變更狀態
Action 可以包含任意異步操作
Action 函數的第一個參數是與 store 實例具有相同方法和屬性的 context 對象,第二個參數是載荷,如果是多個參數的話,載荷就是一個對象
Action 通過 store.dispatch 方法觸發
Actions 支持同樣的載荷方式和對象方式進行分發
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')`
})
}
}
//如果我們利用 async / await,我們可以如下組合 action:
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}