momo's Blog.

[学习笔记]Vuex入门

字数统计: 582阅读时长: 3 min
2021/05/20 Share

State

在组件中获得Vuex状态

我们只需要在全局Vue对象中,指定属性store即可, vue会自动注册到每个字组件中. 子组件通过 this.$store 访问

mapState 辅助函数

当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,

// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',

// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
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
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.6.2/dist/vuex.js"></script>
</head>

<body>
<div id="app">
<button @click="increment()">aaa</button>
{{ count }} {{ c }}
</div>
<script>

const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})

const app = new Vue({
el: '#app',
computed: Vuex.mapState({
count: a => a.count,
c: "count"
}),
methods: {
increment() {
this.$store.commit('increment')
console.log(this.$store.state.count)
}
},
store,
})



</script>
</body>

</html>

Getter

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
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.6.2/dist/vuex.js"></script>
</head>

<body>
<div id="app">
<button @click="increment()">aaa</button>
</div>
<script>

const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}

}
})

const app = new Vue({
el: '#app',
mounted () {
console.log(this.$store.getters.doneTodos)
},
store,
})



</script>
</body>

</html>
CATALOG
  1. 1. State
    1. 1.1. 在组件中获得Vuex状态
    2. 1.2. mapState 辅助函数
  2. 2. Getter