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'], {
// ...
})