Vue中mapMutations传递参数方式是什么

发布时间:2022-04-12 13:45:46 作者:iii
来源:亿速云 阅读:369

本篇内容主要讲解“Vue中mapMutations传递参数方式是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue中mapMutations传递参数方式是什么”吧!

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

在…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>
    <h5>这里是son1组件</h5>
    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))
        }
    }
}

到此,相信大家对“Vue中mapMutations传递参数方式是什么”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. vue路由跳转怎么传递参数
  2. Python中有哪些传递参数的方式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue mapmutations

上一篇:java接口组成更新怎么实现

下一篇:Java中怎么使用wait和notify实现线程间的通信

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》