Vuex: Getters usage instance, vuexgetters instance
1. What is getters?
In the introduction of state, we learned that inStoreWarehouse,stateIt 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 isgettersMeaning of existence. We can think that [getters] is the computing attribute of store.
2. How to Use
Definition: we canstoreDefinitiongettersThe first parameter is state.
const getters = {style:state => state.style}
Parameter passing: definedGettersExposedstore.gettersObject. You can also accept othergettersAs the second parameter;
Usage:
computed: {doneTodosCount () { return this.$store.getters.doneTodosCount}
3. mapGetters
mapGettersThe Helper function onlystoreIngettersMaps to local computing attributes. Usage andmapStateSimilar
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
wrapGettersInitializationgetters, Three parameters are accepted,storeIndicates the currentStoreInstance,moduleGettersAllgetters,modulePathPath 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.