Vuex 四个map方法的使用
原始的写法:
//state
{{ $store.state.属性名}}
//actions
this.$store.dispatch("方法名", 参数);
//mutations
this.$store.commit("参数名",值);
//getters
{{ $store.getters.方法名 }}
现在可以通过map去映射对应的方法不需要再去写this.$stroe......
1、引入map对象
import { mapState, mapActions, mapMutations, mapGetters } from "vuex";
mapState对应state,
mapActions对应actions;
mapMutations对应mutations;
mapGetters对应getters;
需要用到哪个引入对应的就可以了
2、使用方法
注意点:
mapState和mapGetters建议在computed计算属性中去使用这样更容易监测数据的变化
开始使用
这四个map虽然名字不一样但是使用方法都是类似的,这里的map有两种写法
第一种:
在对象的参数中去使用对象的方法去映射
键:当前页面使用的方法名
值:vuex中对应的方法名
...mapMutations({
addNumber: "NUMBER_INCREASE",
minusNumber: "NUMBER_MINUS",
}),
第二种:
在对象的参数中去使用数组的方法去映射
当前页面使用的方法名和vuex文件中的方法名都相同时采用此写法
...mapMutations(['NUMBER_INCREASE','NUMBER_MINUS']),
传递参数:
在调用方法的时候通过参数的方法进行传递
例如:
//标签中
<button @click="addNumber(number)">点我数字+1</button>
//代码中
this.addNumber(this.number)