Vue中mapMutations傳遞參數(shù)方式
通過子組件定義的方法傳遞參數(shù)
在…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>
? ? <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>當(dāng)然也可以寫直接傳遞
state.age = params
<button @click="changeName(555555)">改名字</button>
省略data傳參
...mapMutations(["changeName"])
關(guān)于mapMutations的作用
mapMutations工具函數(shù)會將store中的commit方法映射到組件的methods中。和mapActions的功能幾乎一樣,我們來直接看它的實現(xiàn):
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
}函數(shù)的實現(xiàn)幾乎也和 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')
?? ??? ?})
?? ?}
}經(jīng)過mapMutations函數(shù)調(diào)用后的結(jié)果,如下所示:
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))
?? ??? ?}
?? ?}
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用proxytable 配置解決 vue-cli 的跨域請求問題【推薦】
這篇文章主要介紹了利用 proxytable 配置解決 vue-cli 的跨域請求問題,本文的目錄結(jié)構(gòu)基于 webpack 模板結(jié)構(gòu),需要的朋友可以參考下2018-05-05
vue-cli腳手架打包靜態(tài)資源請求出錯的原因與解決
這篇文章主要給大家介紹了關(guān)于vue-cli腳手架打包靜態(tài)資源請求出錯的原因與解決方法,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用vue-cli具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
vue3使用xgPalyer實現(xiàn)截圖功能的方法詳解
這篇文章主要為大家詳細介紹了如何在vue3中使用xgPalyer截圖功能,以及自定義插件,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02

