Vuex核心API总结
什么是Vuex
vuex是一个专门为vue.js应用程序开发的状态管理模式,采用集中式存储管理应用的所有组件的状态,解决多组件应用通信问题.(简单来说是vue官方提供的独立于组件之外的,管理公共数据的工具).
Vuex核心内容
(1)state:统一定义公共数据,是响应式的,如修改,视图上的值也会发生变化
(2)mutations:用于修改数据,是Vuex中用来修改数据的唯一入口
(3)getters:在state数据基础上,进一步对数据进行加工处理得到新的数据
(4)actions:可以通过mutations来修改state数据,而不是直接改变状态;可以包含任意异步操作(如ajax操作)
(5)modules:模块拆分,把复杂的场景按模块拆分成多个文件
如何使用全局state
(1)直接使用:this.$store.state.xxx
(2)map函数:computed:{
...mapState(['xxx'])
...mapState({'新名字':'xxx'})
}
如何使用modules中的state(namespaced:true)
(1)直接使用:this.$store.state.modules名.xxx
(2)map函数:computed:{
...mapState('modules名',['xxx'])
...mapState(''modules名,{'新名字':'xxx'})
}
如何使用全局mutations
(1)直接使用:this.$store.commit('mutations名',实参)
map函数:methods:{
...mapMutations(['mutations名'])
...mapMutations({'新名字':'mutations名'})
}
如何使用modules中的mutations(namespaced:true)
(1)直接使用:this.$store.commit(['modules名/mutations名'])
(2)map函数:methods:{
...mapMutations('modules名',['mutations名'])
...mapMutations('modules名',{'新名字':'mutations名'})
}
如何使用全局getters
(1)直接使用:this.$store.getters.getter名
(2)map函数:computed:{
...mapGetter(['getter名'])
...mapGetter({'新名字':'getter名'})
}
如何使用modules中的getters(namespaced:true)
(1)直接使用:this.$store.getters.modules名.getter名
(2)map函数:computed:{
...mapGetters('getter名',['getter名'])
...mapGetters('getter名',['新名字':'getter名'])
}
如何使用全局actions
(1)直接使用:this.$store.dispatch('action名',实参)
(2)map函数:methods:{
...mapActions(['action名'])
...mapActions({'新名字':'action名'})
}
如何使用modules中的actions(namespaced:true)
(1)直接使用:this.$store.dispatch('module名/action名',实参)
(2)map函数:methods:{
...mapActions('module名',['action名'])
...mapActions('module名',{'新名字':'action名'})
}
图示如下:
附1 state,mutations和actions关系图: