// store/index.js
mutations: {
changeCount(state){
state.count=3000;
},
},
actions: {
changeCount3000s(context){
setTimeout(()=>{
context.commit('changeCount')
},3000)// Index组件
<button @click="changeCount3000s">点击按钮3s后count的值改变</button>
methods:{
...mapMutations(['add']),
changeCount3000s(){
this.$store.dispatch('changeCount3000s');
}
}
我们在点击按钮3s后count的值改变为3000,我们可以通过this.$store.dispatch(方法名)来触发事件,也可以通过辅助函数mapActions来触发。
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
methods:{
...mapMutations(['add']),
...mapActions(['changeCount3000s'])
}学会以上几个属性的使用基本就可以满足平时业务中的需求了,但使用Vuex会有一定的门槛和复杂性,它的主要使用场景是大型单页面应用,如果你的项目不是很复杂,用一个bus也可以实现数据的共享,但是它在数据管理,维护,还只是一个简单的组件,而Vuex可以更优雅高效地完成状态管理,所以,是否使用Vuex取决于你的团队和技术储备。
参考资料:
《Vue.js实践》 Vuex










