Vuex是什么?
Vuex是一个专门为Vue.js应用设计的状态管理架构,统一管理和维护各个vue组件的可变化状态。
它有五个核心概念:state
,getters
,mutations
,actions
,modules
。
总结
- state ---> 基本数据
- getters ---> 从基本数据派生的数据
- mutations ---> 提交更改数据的方法,同步!
- actions ---> 像一个装饰器
- modules ---> 模块化vuex
State
- state:Vuex中的基本数据
单一状态树
- vuex使用单一状态树,即用一个对象就包含了全部的状态数据。
state
作为构造器选项,定义了所有需要的基本状态参数。
在Vue组件中获得vuex属性
- 可以通过Vue的
computed
获得Vuex的state,如下:
在store/index.js中:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:56
},
mutations: {
},
actions: {
},
modules: {
}
})
在组件HelloWorld.vue中获取count
属性
computed:{
count(){
return this.$store.state.count
}
}
- mapState辅助函数
- 当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,可以使用到mapState辅助函数来生成计算属性,可以少按几次键。。。
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from "vuex";
export default {
name: "XXX",
data() {
return {
localCount: 87,
};
},
computed: mapState({
// 箭头函数可使代码更简练
count: (state) => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: "count",
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState(state) {
return state.count + this.localCount;
},
}),
};
- 当映射的计算属性的名称与state的子节点名称相同时,也可以给mapState传一个字符串数组。
import { mapState } from "vuex";
export default {
name: "xxx",
computed: mapState(['count']),
};
- 对象展开运算符
mapState函数返回的是一个对象。如何将它与局部计算属性混合使用呢?通常,是需要使用一个工具函数将多个对象合并为一个,这样可以将最终对象传给computed属性。但有了对象展开运算符,可以大大地简化写法:
computed: {
localComputed() {
// 本地计算属性
return "";
},
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
//...
}),
},
组件仍然保有局部状态
- 使用vuex并不意味着需要将所有的状态放入vuex。虽然将所有的状态放到vuex会使状态变化更显示和易调试,但也会使代码变得冗长和不直观。
- 如果有些状态严格属于单个组件,最好还是作为组件的局部状态。
- 这应该根据自己的应用开发进行权衡和确定。
getters
- 从store的
state
中派生出的状态。
- getters接收state作为其第一个参数,接收其他getters作为第二个参数,如不需要,第二个参数也可以省略。
store/index.js如下:
export default new Vuex.Store({
state: {
count: 56,
},
getters: {
countDouble(state) {
return state.count * 2
},
countDoubleAndDouble(state, getters) {
return getters.countDouble * 2
},
},
mutations: {},
actions: {},
modules: {},
})
- 与state一样,也可以通过Vue的
computed
获得vuex的getters。
组件XXX.vue如下:
computed: {
count() {
return this.$store.state.count;
},
countDouble() {
return this.$store.getters.countDouble;
},
countDoubleAndDouble() {
return this.$store.getters.countDoubleAndDouble;
},
},
mapGetters 辅助函数
- mapGetters辅助函数仅仅是将store中的getters映射到局部计算属性,与state相似。
import { mapGetters } from "vuex";
export default {
name: "XXX",
computed: {
// 使用对象展开运算符将 getters 混入 computed 对象中
...mapGetters(["countDouble", "countDoubleAndDouble"]),
},
};
- 如果想将一个getter属性另取名字,可以使用对象的形式:
...mapGetters({
double: "countDouble",
countDoubleAndDouble: "countDoubleAndDouble",
}),
mutations
- 提交mutations是更改vuex中的状态的唯一方法。
- mutations必须是同步的,如果要异步需要使用
action
- 每个mutations都有一个字符串的事件类型(type)和一个回调函数(handler)。这个回调函数就是实际进行状态更改的地方,并且它会接受state作为第一个参数,提交荷载作为第二个参数(大多数情况下是一个对象,可以省略)
const store = new Vuex.Store({
// 所有的数据都放在state中
state: {
count: 45
},
// 操作数据,唯一的通道是mutations
mutations: {
// 无提交荷载
increment(state) {
state.count++
},
// 提交荷载
incrementN(state, obj) {
state.count += obj.n
}
},
// actions,可以来做异步操作,然后提交给mutations,而后再对state(数据)进行操作
actions: {}
})
- 但是不能调用一个mutations handler。这个选项更像是事件注册:“当触发一个类型为increment的mutation时,调用此函数。”要唤醒一个mutation handler,需要以相应的
type
调用store.commit
方法:
// 无提交荷载
store.commit('increment')
// 提交荷载
store.commit('incrementN', {
n: 100
})
对象风格的提交方式
store.commit({
type: 'incrementN',
n: 29
})
mutations 需遵循 Vue 的响应原则
- 最好提前在 store 中初始化好所有所需属性;
- 当需要在对象上添加新属性时,应该
- 使用
Vue.set(obj,'newProp',123)
,或者 - 以新对象替代老对象。
例如:利用对象展开运算符可以这样写:state.obj = {...state.obj, newProp:123}
- 使用
mapMutations 辅助函数
- 与其他辅助函数相似,可以在组件中使用
this.$store.commit('xxx')
提交mutation,或者使用mapMutations辅助函数将组件中的methods映射为store.commit 调用(需要在根节点注入store)
import { mapState, mapMutations } from 'vuex'
export default {
name: 'Demo',
computed: {
...mapState(['count'])
},
methods: {
...mapMutations([
// 映射 this.increment() 为 this.$store.commit('increment')
'increment'
]),
...mapMutations({
// 映射 this.add() 为 this.$store.commit('increment')
add: 'incrementN'
})
}
}
actions
- Action类似于mutation,不同在于:
- Action提交的是mutation,而不是直接变更状态;
- Action 可以包含任意异步操作。
举个例子:
const store = new Vuex.Store({
// 所有的数据都放在state中
state: {
count: 45
},
// 操作数据,唯一的通道是mutations
mutations: {
// 无提交荷载
increment(state) {
state.count++
}
},
// actions,可以来做异步操作,然后提交给mutations,而后再对state(数据)进行操作
actions: {
increment(context) {
setInterval(() => {
context.commit('increment')
}, 1000)
}
}
})
注意:
Action
函数接受一个与store实例具有相同方法和属性的context
对象, 因此可以调用context.commit
来提交一个mutation
,或者通过context.state
和context.getters
来获取 state 和 getters。
分发actions
- Action 通过
store.dispatch
方法触发:
store.dispatch('increment')
其他与mutations类似的地方
- Actions支持同样的荷载方式和对象方式进行分发:
// 以载荷形式分发
store.dispatch('incrementN', {
n: 10
})
// 以对象形式分发
store.dispatch({
type: 'incrementN',
n: 10
})
mapActions 辅助函数
- 在组件中可以使用
this.$store.dispatch('xxx)
分发action; - 也可以使用
mapActions
辅助函数将组件的methods映射为store.dispatch
调用(需要先在根节点注入 store)
import { mapActions } from 'vuex'
export default {
//..
methods: {
...mapActions([
'incrementN' //映射 this.incrementN() 为 this.$store.dispatch('incrementN')
]),
...mapActions({
add: 'incrementN' //映射 this.add() 为 this.$store.dispatch('incrementN')
})
}
}
Modules
- 使用单一状态树,导致应用的所有状态集中到一个很大的对象。但是,当应用变得很大时,store 对象会变得臃肿不堪。
- 为了解决以上问题,Vuex 允许我们将 store 分割到模块(module)。
- 每个模块拥有自己的 state、mutation、action、getters、甚至是嵌套子模块——从上至下进行类似的分割:
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
,接收的第一个参数是模块的局部状态,对于模块内部的getter
,根节点状态会作为第三个参数:
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// state 模块的局部状态
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
},
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}
- 同样,对于模块内部的 action,context.state 是局部状态,根节点的状态是 context.rootState:
const moduleA = {
// ...
actions: {
incrementIfOddOnRootSum (context) {
if ((context.state.count + context.rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}