vuex
父向子传值
: v-bind属性绑定子向父传值
: v-on属性绑定兄弟组件之间数据共享
: EventBus- $on 接受数据的那个组件
- $emit 发生数据的那种组件
vuex是实现组件数据共享的机制,组件之间的数据共享
。
- 便于维护和开发
- 组件之间数据共享
- 响应式,能够保持数据与页面的同步
访问state数据
- 1 $store.state.count
- 2 使用mapState
1. 导入mapState
2. 将导入的mapState,映射到当前组件的computed计算属性中
computed: {
...mapState(['count'])
}
mutations
- 只能mutations变更store数据,不可以直接操作。
- 好处在于,可以监控所以的数据变化
触发mutation方式
- this.$store.commit()
- mapMutations
// 1. 定义mutation
addN (state, step) {
state.count += step
},
// 2. 发起调用mutation
// this.$store.state.count++ // error
this.$store.commit('add')
// 另一种方式
...mapMutations(['sub', 'subN']) // 在事件中直接调用 或定义函数 this.sub()
不要在mutation中执行代码,需要使用Action进行处理异步数据。
Action
用于处理异步任务
处理ActioN - mutattion - state
- this.$sore.dispatch(‘addAsync’)
- 通过mapActions
// 在事件中调用
// dispatch函数, 专门用来触发action
this.$store.dispatch('addAsync')
// store.js
addAsync (context) {
setTimeout(function () {
// 在actions中, 不能直接修改state中的数据
// 需要通过 context.commit() 处理某个mutation才可以
context.commit('add')
}, 1000)
},
Getter
对store已有的数据加工处理之后形成新的数据,类似VUE的计算属性。
不会修改store的数据
使用
// $store.getters.showNum
// store.js
getters: {
showNum (state) {
return '当前的数量是:' + state.count
}
}