Vuex 允許我們在store中定義“getter”(可以認為是store的計算屬性)。就像計算屬性一樣,getter的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變才會被重新計算。
getters的作用
對於getters的理解主要作用是對state屬性進行計算,可以理解類似於Vue中computed。接下來讓我通過一個例子如何使用這兩個功能的。
還是以我們上一講的累加器為例,在getter.js中增加getCount,內容如下:
1
2
3
4
5
6
7
8
9
10
|
const getters = {
getNum (state) {
return
state.num
},
getCount (state) {
return
state.count
}
}
export
default
getters
|
在組件中如何使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<template>
<div
class
=
"getter"
>
{{ count }}
<button @click=
"add"
>ADD State</button>
</div>
</template>
<script>
export
default
{
data () {
return
{}
},
computed: {
count () {
return
this
.$store.getters.getCount
}
},
methods: {
add () {
this
.$store.commit(
'add'
)
}
}
}
</script>
|
this.$store調用
1
|
this
.$store.getters.getCount
|
引用store來調用
1
2
3
|
import
store from
'@/store/store.js'
store.getters.getCount
|
mapGetters 輔助函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<template>
<div
class
=
"getter"
>
{{ getCount }}
<button @click=
"add"
>ADD State</button>
</div>
</template>
<script>
import
{ mapGetters } from
'vuex'
export
default
{
data () {
return
{}
},
computed: {
...mapGetters([
'getCount'
])
},
methods: {
add () {
this
.$store.commit(
'add'
)
}
}
}
</script>
|