vuex中getter的用法


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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM