Vuex: Getters usage instance, vuexgetters instance
1. What is getters?
In the introduction of state, we learned that inStore
Warehouse,state
It is used to store data. If the data is processed and output, for example, to filter the data, we can writecomputed
. However, if many components use the filtered data, such as the pie chart component and the graph component, can we extract and share the data? This isgetters
Meaning of existence. We can think that [getters] is the computing attribute of store.
2. How to Use
Definition: we canstore
Definitiongetters
The first parameter is state.
const getters = {style:state => state.style}
Parameter passing: definedGetters
Exposedstore.getters
Object. You can also accept othergetters
As the second parameter;
Usage:
computed: {doneTodosCount () { return this.$store.getters.doneTodosCount}
3. mapGetters
mapGetters
The Helper function onlystore
Ingetters
Maps to local computing attributes. Usage andmapState
Similar
Import {mapGetters} from 'vuex' computed: {// use the object expansion operator to mix getters into the computed object... mapGetters (['donetodoscount ', 'anothergetter',])} // change the getter attribute name to mapGetters ({// ing this. doneCount is store. getters. doneTodosCount doneCount: 'donetodoscount '})
4. Source Code Analysis
wrapGetters
Initializationgetters
, Three parameters are accepted,store
Indicates the currentStore
Instance,moduleGetters
Allgetters
,modulePath
Path of the corresponding module
Function 'wrapgetters '(store, moduleGetters, modulePath) {Object. keys (moduleGetters ). forEach (getterKey => {// traverse all the first getters const rawGetter = moduleGetters [getterKey] if (store. _ wrappedGetters [getterKey]) {console. error ('[vuex] duplicate getter key: $ {getterKey}') // The key of getter cannot be repeated. Otherwise, an error is returned. _ wrappedGetters [getterKey] = function 'wrappedgetter '(store {// wrap each getter into a method and add it to stor E. in the _ wrappedGetters object, return rawGetter (// executes the getter callback function and passes in three parameters (local state, store getters, rootState) getNestedState (store. state, modulePath), // local state // find the nested state store on the state according to the path. getters, // store all getters store. state // root state)} // find the nested state function 'getnestedstate' (state, path) {return path based on the path. length? Path. reduce (state, key) => state [key], state): state}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.