Home >Web Front-end >Vue.js >Learn more about State and Getters in Vuex
The internal organs of Vuex are composed of five parts: State, Getter, Mutation, Action and Module. This article will first give you an in-depth understanding of State and Getter in Vuex. I hope it will be helpful to you!
Vuex is a state management tool for vue, in order to make it more convenient for multiple components to share state. [Related recommendations: "vue.js Tutorial"]
npm install vuex --save复制代码
import Vue from 'vue';import Vuex from 'vuex'; Vue.use(Vuex);const store = new Vuex.Store({ state: { count: 0 } })new Vue({ store, })
Single state tree, Use a single object to contain all application-level state.
Vuex provides a mechanism to "inject" state from the component into each sub-component through the store option (call Vue.use(Vuex )).
By registering the store option in the root instance, the store instance will be injected into all sub-components under the root component, and the sub-components can be accessed through this.$store.
1832d1c4a53e5db59fd2eed60b317a8f {{ $store.state.count }}16b28748ea4df4d9c2150843fecfba68复制代码
When a component needs to obtain multiple states, declaring these states as computed properties will be somewhat repetitive and redundant. In order to solve this problem, we can use the mapState helper function to help us generate calculated properties:
import { mapState } from 'vuex'; computed: { ...mapState(['count']), },
Use a different name:
computed: { ...mapState({ storeCount: state => state.count, // 简写 storeCount: 'count', // 等同于 state => state.count }), },
store the calculated properties. The return value of the getter will be cached according to its dependencies, and will only be recalculated when its dependency values change.
Getter receives state as its first parameter and getters as its second parameter.
getters: { doubleCount (state) { return state.count * 2; } }
The Getter will be exposed as a store.getters object: this.$store.getters.doubleCount
You can also let the getter return a function to pass parameters to the getter
getters: { addCount: state => num => state.count + num; }
this.$store.addCount(3);
import { mapsGetters } from 'vuex'; export default { computed: { ...mapGetters([ 'doubleCount', 'addCount', ]) } }
If you want to give a getter attribute another name, use the object form :
mapGetters({ // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount` storeDoubleCount: 'doubleCount' })
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of Learn more about State and Getters in Vuex. For more information, please follow other related articles on the PHP Chinese website!