mapMutations传递参数

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

mapMutations传递参数

欧冠开了   2022-05-28 我要评论

通过子组件定义的方法传递参数

在…mapMutations引用

不多逼逼,看代码!

store文件中:

import Vuex from 'vuex';
import Vue from 'vue';
Vue.use(Vuex);
let store = new Vuex.Store({
    state: {
        name: 'hahahah',
        age: '19',
    },
    mutations: {
        changeName(state, params) {
            console.log(params);
            state.name = params.name 
        },
        changeAge(state, params) {
            state.age = params.age
        }
    },
})
export default store

VueDemo中:

<template>
  <div>
    <h4>这里是son1组件</h4>
    name:{{name}}
    age:{{age}}
    <button @click="hehe">改名字</button>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      list: {
        name: "6666"
      }
    };
  },
  computed: {
    ...mapState(["name", "age"])
  },
  methods: {
    hehe() {
      this.changeName(this.list);
    },
    ...mapMutations(["changeName"])
  }
};
</script>
<style>
</style>

当然也可以写直接传递

state.age = params
<button @click="changeName(555555)">改名字</button>

省略data传参

...mapMutations(["changeName"])

关于mapMutations的作用

mapMutations工具函数会将store中的commit方法映射到组件的methods中。和mapActions的功能几乎一样,我们来直接看它的实现:

export function mapMutations (mutations) {
    const res = {}
    normalizeMap(mutations).forEach(({ key, val }) => {
        res[key] = function mappedMutation (...args) {
            return this.$store.commit.apply(this.$store, [val].concat(args))
        }
    })
    return res
}

函数的实现几乎也和 mapActions 一样,唯一差别就是映射的是 store 的 commit 方法。为了更直观地理解,我们来看一个简单的例子:

import { mapMutations } from 'vuex'
export default {
    // ...
    methods: {
        ...mapMutations([
            'increment' // 映射 this.increment() 到 this.$store.commit('increment')
        ]),
        ...mapMutations({
            add: 'increment' // 映射 this.add() 到 this.$store.commit('increment')
        })
    }
}

经过mapMutations函数调用后的结果,如下所示:

import { mapActions } from 'vuex'
export default {
    // ...
    methods: {
        increment(...args) {
            return this.$store.commit.apply(this.$store, ['increment'].concat(args))
        }
        add(...args) {
            return this.$store.commit.apply(this.$store, ['increment'].concat(args))
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们