In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "vue how to use Vuex state management mode", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how vue uses Vuex state management mode" article.
1. Vuex is generated based on the problem of unidirectional data flow.
Unidirectional data flow is the core concept of parent-child components in vue, and props is unidirectionally bound. When the property value of the parent component changes, the corresponding change will be passed to the child component, thus forming an one-way downlink binding, and the property change of the parent component will flow to the downlink child component, but on the contrary, in order to prevent the child component from inadvertently modifying the data in the parent component and affecting the state of other child components, vue stipulates that the bottom-up data flow is not allowed. When our application encounters multiple components sharing state, the simplicity of one-way data flow is easily broken:
A. Multiple components depend on the same state. Passing parameters between components becomes particularly tedious, and state transfer between sibling components is powerless.
B. behaviors from different views need to change the same state. Multiple copies of the state are often changed and synchronized using parent-child components directly referenced or through events.
Why don't we extract the shared state of the component and manage it in a global singleton pattern? Vuex is a state management model developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way.
Using Vuex doesn't mean you need to put all your states into Vuex. Although putting all states into Vuex makes the state changes more explicit and easier to debug, it also makes the code lengthy and unintuitive. If some states belong strictly to a single component, it is best to act as a local state of the component. It should be weighed and determined according to your application development needs.
2. Install and use CDN: NPM: npm install vuex-- save Yarn: yarn add vuex other ways: project initialization is the introduction of dependencies. Either way, Vue.use (Vuex) is required to install Vuex3, core and usage.
The core of every Vuex application is store. "store" is basically a container that contains the Vuex core State, Getters, Mutation, Action, Module of most of the state vuex in your application.
(1) State
Vuex also uses a single state tree to manage all states at the application level. Unique data source.
A single state tree allows us to find fragments of a state in the most direct way, and it can also be easily managed and maintained during subsequent maintenance and debugging.
State storage state is similar to data in a component. There are often two ways to access state in a component:
A, through this.$store.state. Property to access the state, which is usually written in the computed evaluation property, but can also be accessed directly through interpolation expressions
B, with the help of mapState auxiliary function.
The core code is as follows:
{{mycount}}
Direct interpolation expression access {{this.$store.state.count}}
{{myinfoAge}}
Import Vue from 'vue'; import Vuex from' vuex' Import {mapState} from 'vuex'// must remember to introduce const store = new Vuex.Store ({/ / store state data state: {count: 0, info: {name: "xiaoming" when using helper functions Age:18}},) new Vue ({el:'# app', store, computed: {/ / a, mycount () {return this.$store.state.count}) / / b. Use auxiliary functions to assign values to corresponding variables The page can use this variable directly... mapState ({myinfoAge: (state) = > state.info.age,}), / / when the name of the mapped calculation attribute is the same as the name of the child node of state, we can also pass mapState an array of strings. The following simplified writing is equivalent to info: (state) = > state.info,... mapState (["info"]),}}) (2) Getters
A calculation property of store, analogous to the calculation property of a component, the return value of getter is cached according to its dependency and will be recalculated only if its dependency value is changed. Getter accepts state as its first parameter, the data in state changes, and the calculation property is recalculated.
The state storage of Getters is equivalent to the calculated attributes in the component, and can be accessed in three ways:
A, access through attributes
B. Access through method
C. Access through mapGetters helper function
The core code is as follows:
{{myInfoLength}}
Direct interpolation expression access {{this.$store.getters.infoLength}}
{{myName}}
{{infoLength}} import Vue from 'vue'; import Vuex from' vuex' Import {mapGetters} from 'vuex'// must remember to introduce const store = new Vuex.Store ({state: {info: [{name: "name1", age:18}, {name: "name2", age:28}]} when using auxiliary functions. / / Storage status data getters: {infoLength: (state) = > {return state.info.length }, getNameByAge: (state) = > (age) = > {return state.info.find (item = > item.age = age) .name}},) new Vue ({el:'# app', store Computed: {/ / a, access myInfoLength () {return this.$store.getters.infoLength} / / b through attributes Access myName () {return this.$store.getters.getNameByAge (18)} / / c through the method, and the mapGetters helper function simply maps the getter in store to a local calculation attribute. MapGetters (["infoLength"])}}) (3) Mutation
The previous two core concepts of state and getters are for the use of storing and accessing data in store, while Mutation provides the function of modifying the data in store and is the only way to update it. The submission Mutation,Mutation mainly consists of two parts: the event type of the string (type) and a callback function (handler). The first parameter of the callback function is state.
You cannot directly modify the state in the store container in the view component. You need to register an event function in the container first. When you need to update the status, you need to submit and trigger the event, and you can pass parameters to the event. Here you need to distinguish it from the two-way binding of v-model within the component. There are several ways to submit events:
A, ordinary submission method
B. Object style submission
C, with the help of mapMutations auxiliary function
The core code is as follows:
Click I add a little I add objects add objects add import Vue from 'vue'; import Vuex from' vuex' Import {mapMutations} from 'vuex'// must remember to introduce const store = new Vuex.Store ({state: {count:1}, mutations: {/ / register event addCount (state) {state.count + +}) when using helper functions AddCountForNum (state,num) {state.count + = num}, addCountForObj (state,payload) {state.count + = payload.num} AddMap (state) {state.count + +}}) new Vue ({el:'# app', store Methods: {/ / a, ordinary submission method handleAdd () {this.$store.commit ('addCount')}, handleAddForNum () {this.$store.commit (' addCountForNum',10)} / / b, object style submission handleAddForObj () {this.$store.commit ({type: "addCountForObj", num: 100}) }, / / c, with the aid of the mapMutations helper function... mapMutations (["addMap"]), handleAddMap () {this.addMap ()})
Mutation needs to follow the response rules of Vue, and the state in the store of Vuex is responsive, so when we change the state, the Vue component that monitors the status will be updated automatically. This also means that mutation in Vuex needs to follow the same caveats as using Vue: it's best to initialize all the required attributes in your store in advance. When you need to add new properties to an object, you should use Vue.set (obj, 'newProp', 123), or replace the old object with the new object. For example, use the object expansion operator state.obj = {... state.obj, newProp: 123}
Note: Mutation must be a synchronization function. Mixing asynchronous calls in mutation can make your program difficult to debug. For example, when you call two mutation with asynchronous callbacks to change the state, how do you know when the callback is and which callback is the first?
(4) Action
Action is similar to Mutation, but is used to replace the asynchronous operation of Mutation. Action is used to modify state asynchronously, which modifies state indirectly through muation.
A context is an object that has the same methods and properties as a store object. In other words, we can do commit-related operations through context, and we can also get context.state and so on.
If you need an asynchronous operation to modify the state in state, you first need action to register the event. The component view calls the event through dispatch distribution, and the event is submitted internally to mutation to complete the state change operation. In short, the event function in mutation is submitted through the mediation of action. The method of distributing events is as follows:
A, ordinary submission method
B. Object style submission
C, with the help of mapActions auxiliary function
The core code is as follows:
Click me to add a little bit I add ten objects to add objects to add import Vue from 'vue'; import Vuex from' vuex' When import {mapMutations,mapActions} from 'vuex'// uses an auxiliary function, remember to introduce const store = new Vuex.Store ({state: {count:1}) / / Registration event modifies state status value mutations: {addCount (state) {state.count + +}, addCountForNum (state,num) {state.count + = num}, addCountForObj (state) Payload) {state.count + = payload.num}, addMap (state) {state.count + +}}, / / register the event Submit to mutation actions: {addAction (context) {setTimeout (()) = > {context.commit ('addCount')}, 1000)}, addActionForNum (context) Num) {setTimeout (() = > {context.commit ('addCountForNum',num)}, 1000)}, addActionForObj (context,payload) {setTimeout (()) = > {context.commit (' addCountForObj',payload)} 1000)}, addActionMap (context) {setTimeout (() = > {context.commit ('addMap')}, 1000)}) new Vue ({el:' # app', store Methods: {/ / a, ordinary submission method handleAdd () {this.$store.dispatch ('addAction')}, handleAddTen () {this.$store.dispatch (' addActionForNum',10)} / / b, object style submission handleAddForObj () {this.$store.dispatch ({type: 'addActionForObj') Amount: 10})} / / with the help of the mapActions helper function... mapActions (["addActionMap"]) / / equivalent to... mapActions ({addActionMap: "addActionMap"}) handleAddMap () {this.addActionMap ()})
Composite Action: combine multiple action to handle more complex asynchronous processes. Store.dispatch can handle the Promise returned by the handler of the triggered action, and the store.dispatch still returns Promise. A store.dispatch can trigger multiple action functions in different modules. In this case, the returned Promise executes only after all triggering functions are completed. Suppose getData () and getOtherData () return Promise.
Actions: {async actionA ({commit}) {commit ('gotData', await getData ())}, async actionB ({dispatch, commit}) {await dispatch (' actionA') / / wait for actionA to complete commit ('gotOtherData', await getOtherData ())} (5) Modules
Vuex allows us to split store into modules (Module), and each module has its own state, mutation, action, getters, etc.
4. The difference between Vuex and global objects
(1) the state storage of Vuex is responsive. When the Vue component reads the state from the store, if the state in the store changes, then the corresponding component will be updated efficiently accordingly.
(2) you cannot directly change the state in store. The only way to change the state in store is to commit the mutation explicitly. This makes it easy for us to track changes in each state, allowing us to implement tools to help us better understand our applications.
The above is about the content of this article on "how vue uses Vuex state management mode". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.