Vuex 是一个专为 Vue.js 开发的状态管理工具,可以实现组件间的数据共享。
1、state
state提供vuex中唯一的公共数据源,所有组件共享的数据都统一放到Store的state中存储。
假如我们需要把一个count数据要存到vuex中,以下代码即可:
state: {
count:0
}
如何在组件中使用?
第一种做法:
<h1> {{$store.state.count}} </h1>
第二种做法:使用vuex提供的mapState函数
computed:{
...mapState(['count'])
}
// 等价于
// computed:{
// count(){
// return this.$store.state.count
// }
// }
<h1> {{showCount}} </h1>
2、mutations
mutations是vuex中唯一合法的用来修改state的方式,但是它不能进行异步操作
假如我们需要定义一个add方法,实现对state中的count加1
mutations: {
add(state){
state.count++
}
}
在组件中如何触发mutations中的add方法呢?
第一种做法:
methods:{
add(){
this.$store.commit('add');
}
}
第二种做法:
methods:{
...mapMutations(['add'])
}
3、actions
actions用于处理vuex中的异步任务
假如我们需要在1秒后才执行mutations中的add方法,可以这样:
actions: {
addAsync(context){
setTimeout(()=>{
context.commit('add');
},1000);
}
}
在组件中怎么触发actions中的方法呢?
第一种做法:
methods:{
addNAsync(n){
this.$store.dispatch('addNAsync',n)
}
}
第二种做法:
methods:{
...mapActions(['addAsync'])
}
4、getters
getters:对于state中的数据进行加工处理形成新的数据
getters: {
showCount(state){
return '当前的count是:【'+state.count+'】';
}
}
在组件怎么使用?
第一种做法:
<h1> {{$store.getters.showCount}} </h1>
第二种做法:
computed:{
...mapGetters(['showCount'])
}
//template中
<h1> {{showCount}} </h1>