# 总结
我们先看一个有无使用mapXXX的demo
没使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/vuex@2.0.0"></script>
</head>
<body>
<div id="app">
<Button @click="handleAdd">添加</Button>
<ul>
<li v-for="num of nums" :key="num">
{{num}}
</li>
</ul>
<h5>最大的: {{ maxNum }}</h5>
</div>
<script>
store = new Vuex.Store({
state: {
nums: []
},
mutations: {
add(state, num) {
state.nums.push(num);
}
},
getters: {
maxNum(state) {
return Math.max(...state.nums);
}
}
})
const { mapState, mapGetters, mapMutations } = Vuex;
new Vue({
el: "#app",
store,
computed: {
nums() {
return this.$store.state.nums;
},
maxNum() {
return this.$store.getters.maxNum;
}
},
methods: {
add(num) {
return this.$store.mutations.commit('add', num);
},
handleAdd() {
const num = parseInt(Math.random()*100);
this.add(num);
}
}
})
</script>
</body>
</html>
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
使用了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/vuex@2.0.0"></script>
</head>
<body>
<div id="app">
<Button @click="handleAdd">添加</Button>
<ul>
<li v-for="num of nums" :key="num">
{{num}}
</li>
</ul>
<h5>最大的: {{ maxNum }}</h5>
</div>
<script>
store = new Vuex.Store({
state: {
nums: []
},
mutations: {
add(state, num) {
state.nums.push(num);
}
},
getters: {
maxNum(state) {
return Math.max(...state.nums);
}
}
})
const { mapState, mapGetters, mapMutations } = Vuex;
new Vue({
el: "#app",
store,
computed: {
...mapState(['nums']),
...mapGetters(['maxNum'])
},
methods: {
...mapMutations(['add']),
handleAdd() {
const num = parseInt(Math.random()*100);
this.add(num);
}
}
})
</script>
</body>
</html>
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
51
52
53
54
55
56
57
58
59
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
51
52
53
54
55
56
57
58
59
通过以上几个map的实现可以总结出这些map实际上帮我们干了以下几件事儿:
- 自动创建了一个以数组元素或者对象key的名称的函数
- 如果有命名空间的,通过命名空间获取对应的
module
- 函数里自动获取
this.$store.xxxx
,然进行this.$store.xxx
的操作
大家从demo中就可以看出,在没有mapXXX
时,vue每次使用store中的任何功能时,都需要重复上述至少两个事情,重复的事情最好一次解决,vuex的mapXXX
就是解决这个问题的,把这些搬砖的事情统一解决了