mapState mapGetter mapMutations使用方式

东明兄 2019-05-17
0条评论 1,834 次浏览
东明兄 2019-05-170条评论 1,834 次浏览

mapState mapGetter mapMutations 是vuex 提供的辅助函数。使用前,需要在组件内先import。

...mapGetter举个例子:

当在一个组件中需要获取vuex上的多个状态时,会这样写:

   computed: {
          systemInfo() {
                return this.$store.getters.systemInfo;
            },
            showNav() {
                return this.$store.getters.getShowNav;
            },
            showTop() {
                return this.$store.getters.getShowTop;
            },
            showBreadcrumb() {
                return this.$store.getters.getShowBreadcrumb;
            },
            operatorInfo: function () {
                return this.$store.getters.getOperatorInfo;
            }
   }

会发现要重复的去 $store 上取数据。

Vue文档:mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性
要获取上方的 systemInfo,可以这样写:mapGetters(['systemInfo'])

打印一下看下输出是什么:

   created() {
            console.log(mapGetters(['systemInfo']));//{systemInfo: ƒ}
   }

mapGetters(['systemInfo']) 返回了一个对象 ,对象里边有一个systemInfo方法。

改成这样:mapGetters(['systemInfo','showNav','showTop','showBreadcrumb','operatorInfo']),
就不用反复去store上取数据了。

mapGetters 返回了一个对象,对象里是vuex中getter对应的方法。

现在将返回的 对象合并到 computed这个对象里边就可以了,使用扩展运算符...展开对象,使得对象内的东西混入到外边的对象(computed)

//扩展运算符 展开对象的例子:
var a = {name:"crazyming",age:23}
console.log({test:"this is a test",...a})//{test: "this is a test", name: "crazyming", age: 23}
   computed: {
...mapGetters(['systemInfo','showNav','showTop','showBreadcrumb','operatorInfo'])
   }

前面我们一个一个在computed定义的方法名称和getter的方法名称不一样(例如:showTop和getShowTop),我这里需要将往mapGetters传入的参数改为对象形式,以便给getter属性改个名字:

   computed: {
       ...mapGetters({
                systemInfo: "systemInfo",
                showNav: "getShowNav",
                showTop: "getShowTop",
                showBreadcrumb: "getShowBreadcrumb",
                operatorInfo: "getOperatorInfo"
            }),
   }

这样就完成了。和上方一个一个定义 computed属性是一样的效果了。

...mapMutations 也一样

 methods: {
            ...mapMutations(['setOperatorInfo']),// 将 `this.setOperatorInfo()` 映射为 `this.$store.commit('setOperatorInfo')`
}

对象的形式:

 methods: {
            ...mapMutations({newName:"setOperatorInfo"}),// 将 `this.newName()` 映射为 `this.$store.commit('setOperatorInfo')`
}

使用方式:

 // this.$store.commit('setOperatorInfo',data);
this.setOperatorInfo(data);  或者 this.newName(data);

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注