mapActions 和 mapMutations

使用方法

1.引入mapActions 和 mapMutations

1
2
import { mapMutations } from 'vuex';
import {mapActions } from "vuex";

2.在methods中调用mapActions和mapMutations方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<template>
<div>
<h1>当前求和为:{{ this.$store.state.sum }}</h1>
<!-- <h1>当前求和放大10倍为:{{ this.$store.state.sum *10 }}</h1> -->
<h1>当前求和放大10倍为:{{ this.$store.getters.calculate }}</h1>
<h1>
我在--{{ this.$store.state.school }},学习--{{
this.$store.state.subject
}}
</h1>

<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<!-- 记得传参 -->
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="odds_add(n)">当前和为奇数再加</button>
<button @click="wait_add(n)">等一等再加</button>
</div>
</template>

<script>
import { mapActions } from "vuex";
import { mapMutations } from "vuex";
export default {
name: "count",
data() {
return {
n: 1, //下拉框选择的数
};
},
methods: {
//靠mapActions生成:odds_add、wait_add(对象形式)
...mapActions({ odds_add: "jia_odd", wait_add: "jia_wait" }),
//靠mapActions生成:odds_add、wait_add(数组形式)
// ...mapActions(['jia_odd','jia_wait']),
//==================================================
//靠mapActions生成:increment、decrement(对象形式)
...mapMutations({ increment: "JIA", decrement: "JIAN" }),
//靠mapMutations生成:JIA、JIAN(对象形式)
// ...mapMutations(['JIA','JIAN']),
},
};
</script>

PS:

mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件(event)对象