Vuex
State
用一個對象就包含了全部的應用層級狀態。
computed:{…};//內存常駐,頻繁的改變
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函數
import { mapState } from 'vuex';
//1
computed: mapState([
// 映射 this.count 爲 store.state.count
'count'
])
//2
// 使用對象展開運算符將此對象混入到外部對象中
...mapState({
// ...
})
Getters
//1
// 使用對象展開運算符將此對象混入到外部對象中
...mapState({
// ...
})
//2 Getters參數設定
Getters 會暴露爲 store.getters 對象:
Getters 也可以接受其他 getters 作爲第二個參數:
//3 store 中的 getters 映射到局部計算屬性
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用對象展開運算符將 getters 混入 computed 對象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
Mutations
每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。
mutation 必須是同步函數
const store = new Vuex.Store({
state: {
count: 1
},
//事件註冊
mutations: {
//參數 state,payload(對象)
increment (state,payload) {
// 變更狀態
state.count++
}
}
})
//事件提交
store.commit('increment',{})
Actions
Action 提交的是 mutation,而不是直接變更狀態。
Action 可以包含任意異步操作。
使用Promise來實現Action的執行,當所有的操作都執行完畢後,就可以返回結果
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
increment ({ commit }) {//參數解析
commit('increment')
}
}
})
Action 通過 store.dispatch 方法觸發:
store.dispatch('increment')
Modules
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
...
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的狀態
store.state.b // -> moduleB 的狀態
對於子模塊訪問根模塊的方式
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
getters: {
sumWithRootCount (state, getters, rootState,rootGetters) {
return state.count + rootState.count
}
}
命名空間
modules: {
account: {
namespaced: true,
},
getters: {
isAdmin () { ... } // -> getters['account/isAdmin']
},
}
state.some.nested.module.a,
...mapActions([
'some/nested/module/foo',
'some/nested/module/bar'
])
模塊的註冊和卸載
// 註冊模塊 `myModule`
store.registerModule('myModule', {
// ...
})
// 註冊嵌套模塊 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
// ...
})