Vuex
0 前言
Vuex的知识有一部分我已经不是很确定。但学习、工作中,模模糊糊确是要不得的,会带来意外的Bug和痛苦的调试。
1 是什么
Vuex是一个状态管理工具。
2 为什么要用它
可以对多个组件间的数据进行统一规范的管理
补充
适用于中大型单页应用,当应用足够简单(使用store模式)时,使用Vuex反而冗余
3 怎么用
3.1 Vuex的结构
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
3.2 state:
从 store 实例中读取状态最简单的方法就是在计算属性 (opens new window)中返回某个状态:
computed:{
count: return $store.state.count
}
Level Up:辅助函数mapState
computed:{
...mapState{
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
}
当计算属性名称与状态子节点名称相同时,可简写
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
3.3 action
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
action中的函数
函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
actions: {
increment (context) {
context.commit('increment')
}
}
事实上,一个action函数还可以通过dispatch触发别的action
actions: {
clickcount(context){
context.dispatch('increment')
context.commit('clickcount')
}.
increment (context) {
context.commit('increment')
}
}
组件中如何触发action
this.$store.dispatch('increment')
// 以载荷形式分发
this.$store.dispatch('incrementAsync', {
amount: 10
})
// 以对象形式分发
this.$store.dispatch({
type: 'incrementAsync',
amount: 10
})
辅助函数(mapAction 与 mapState 同理)
...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')`
})
3.3 mutation
真正修改状态的地方
接受state作为参数,并在函数中对state中的属性进行修改
mutation中的函数
mutations: {
increment (state) {
state.count++
}
},
如何触发
action中和组件中都可以触发
store.commit('increment')
载荷
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)
对象
store.commit({
type: 'increment',
amount: 10
})
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
需要遵循的响应式原则
- 最好提前在你的 store 中初始化好所有所需属性。
- 当需要在对象上添加新属性时,你应该使用 Vue.set(obj, ‘newProp’, 123), 或者以新对象替换老对象。
为什么不能异步
方便地跟踪每一个状态的变化,从而能够实现一些工具帮助更好地了解我们的应用。
具体而言:任何在回调函数中进行的状态的改变都是不可追踪,一旦mutation支持异步操作,状态合适更新就没办法知道。无法很好的追踪状态将为调试带来困难。
未完待续
getter和module还没写,有些晚了,下次继续!