本篇內容主要講解“Vue中mapMutations傳遞參數方式是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Vue中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 storeVueDemo中:
<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工具函數會將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傳遞參數方式是什么”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。