Interpretation of the basic usage of getters
1. Getter definition
Vuex allows us to define "getter" in the store to filter data stored in the state.
Just like computed in the vue life cycle, the return value of getter will be cached according to its dependencies and will be recalculated only if its dependencies change.
2. How to use
1. Access through attributes
Getter accepts state as its first parameter:
Example: Now you need to get the element greater than 5 in list: [1,2,3,4,5,6,7,8,9]
const store = new ({ state:{ list: [1,2,3,4,5,6,7,8,9] } , getters: { getNumber: state => { retrun (item => item > 5) } } })
Use in .vue
computed:{ getNumber(){ return this.$ } }
2. Access through method
The same array list needs to return different data according to different conditions.
By letting getter return a function, pass parameters to getter
const store = new ({ state:{ list: [1,2,3,4,5,6,7,8,9] } , getters: { getNumber: state => (index) => { return (item => item > index) } } })
Use in .vue
computed:{ getNumber(){ return this.$(4) } }
3. Rely on existing getters
example: Get the number of numbers greater than 5 in the list
Note: If getters returns a method, this method cannot be used.
const store = new ({ state:{ list: [1,2,3,4,5,6,7,8,9] } , getters: { getNumber: state => { return (item => item > 6) }, getNumberLength: (state, getters) = > { return } } })
3. mapGetters helper function
The mapGetters helper function simply maps getters in the store to local computed properties:
import { mapGetters } from 'vuex' export default { // ... computed: { // Use the object expansion operator to mix getter into the computed object ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }
If you want to give another name to a getter property, use the object form:
import { mapGetters } from 'vuex' export default { // ... computed: { ...mapGetters({ // Map `` to `this.$` doneCount: 'doneTodosCount' }) } }
4. Things to note about getters
1. The attribute name defined in data cannot be the same as the getter name defined in computed, otherwise an error will be reported.
2. The same name attribute can be defined in state and getter in vuex, without interfering with each other.
Two ways to call getters
Getters and state usage are similar, a bit like the relationship between data and computed in vue
use:
state: { count:0, }, getters:{ countAdd(state){ return + 1 } },
Method 1
this.$
xxx is the name in getters
Method 2
import { mapGetters } from 'vuex' ..... computed:{ ...mapGetters(['countAdd']) }
The above is personal experience. I hope you can give you a reference and I hope you can support me more.