Vuex-Centralized state management architecture specifically designed for Vue.js

Source: Internet
Author: User

Status: Attributes in data need to be shared with other Vue components (that is, properties that need to be shared in data) 1. First knowledge Vuex direct to a small demoThe following operations are based on VUE-CLI, if you do not know the first to learn the next VUE-CLI use NPM Package management tool to install VUEX.    NPM Install Vuex--save Create a new Vuex folder (this is not required) and create a new Store.js file under the folder, introducing our Vue and Vuex into the file.    Import vue from ' Vue ';    Import Vuex from ' Vuex ';    Use our Vuex, and then use Vue.use to refer to it.  Vue.use (VUEX); Through the above operation, Vuex even if the reference succeeds directly to a demo, in the VUE-CLI src directory to create a new folder Vuex, and in this folder to create a new store.js file; directly on the demo
Now we add a constant object in the Store.js file const state={Count:1} with the export default wrapper code, let the external can be referenced. Export default New Vuex.store ({state}) creates a new Vue template, Xxx.vue.        In the template we introduce our newly built Store.js file and output the value of count in the template with {{$store. State.count}}.                <template> <div>  2.state Access State object
In the above example, the const state is the Access status object, which is the shared value between sibling components. The    following is the assignment of the state object to the internal object, that is, the value in the Stroe.js, assigned to our template data in the value of    three kinds of assignment:        First, the calculation of the computed property directly assigned value            computed:{                Count () {                    return this. $store. State.count;                }            }            Template invocation: {{count}}            disadvantage: When a component needs to acquire multiple states, declaring these states as computed properties is somewhat repetitive and redundant.                second, through the Mapstate "object" To assign value            import {mapstate} from ' Vuex ';            The following code is also written in the computed calculation attribute:                computed:mapstate ({                    count:state=>state.count                })        , through Mapstate's Array to assign a value of            computed:mapstate (["Count"])

3.Mutations Modifying state status

1. Mutations equivalent to an object, the object is placed in the event type corresponding callback function, the role is to make state changes, simple understanding is equivalent to an event registration 2.            $store. Commit ()//template call mutations inside the event function value: only need to add a parameter in the mutations, and in the commit time pass can be const mutations={            Add (state,n) {state.count+=n;            , reduce (state) {state.count--;            }} in the Xxx.vue Modify the button's commit () method to pass the parameters, we pass 10, meaning to add 10 each time. <p> <button @click = "$store. Commit (' Add ', ten) ' >+</button> <button @click = "$store. Commit (' reduce ')" >-</button> </p> template Get mutations method actually, we don't like to see $store.        The commit () method appears, and we want to invoke it just like the method in the template.        For example: @click = "reduce" is the same as not referencing the Vuex plug-in.                To achieve this, only a simple two can be used: in the template Xxx.vue with import into our mapmutations:1. In the template Xxx.vue, import our mapmutations with imports:            Import {mapstate,mapmutations} from ' Vuex '; 2. Add the methods attribute to the Script tab of the template and join Mapmutations methods:mapmutationS ([' Add ', ' reduce ']), 3. Call through the above two steps (Note that additional parameters are directly written on) <button @cli ck= "Add (Ten)" >+</button>

4.getters Calculation filter operation

Getters is obtained from the surface and can be seen as a re-edit before the data acquisition (note that the template displays the value after the getters operation) is equivalent to a filtering and processing of the data, which can be regarded as a store.js computed attribute (similar to computed)            The return value of the getter is cached based on its dependency and is recalculated only if its dependency value has changed: The basic usage of 1 is to declare our getters property in Store.js with a const. Const GETTERS = {Count:function (state,getters) {return state.count +=getters.params_get                ter                }, Params_getter:function () {return 1000}} parameter:            State:getters:getters.xxx to pass data from other getters write gettters, we also need to introduce in Vuex.store () Export default New Vuex.store ({state,mutations,getters}) in Store.js        It is finished, we need to configure the computed to the template page in the Vue constructor can only have a computed property, if you write multiple, only the last computed property is available, so the computed property to be a modification.            In the transformation we use the expand operator "..." in ES6. computed:{. Mapstate (["Count"]),//equivalent to an extension of count () {RETurn this. $store. Getters.count; }} "2" with mapgetters simplified template notation: all know that State and mutations have map reference method to simplify the coding in our template, our getters is also the first to use        Import introduces our mapgetters import {mapstate,mapmutations,mapgetters} from ' Vuex '; Add Mapgetters ... mapgetters in the computed property (["Count"])

5.actions Modifying State asynchronously

The actions are basically the same as the previous mutations functions, and the 1.actions commits the mutation instead of changing the state directly.    2.actions is an asynchronous change state, and mutations is a synchronous change. Declaring actions in Store.js can call methods in mutations, call add and reduce two methods in actions the following are two ways to register an event: const ACTI ONS ={addaction (context) {Context.commit (' Add ', ten)}, red                 Uceaction ({commit}) {//Because the context and store instance have the same methods and properties, you can submit mutation commit (' reduce ')            }} wrote two methods in the actions Addaction and reduceaction, in the method body, we all use commit to invoke the method inside the mutations.            Context: Contextual object, where you can understand the store instance itself.                        {Commit}: Pass the Commit object directly to make the method body logic and code clearer. Use <p> <button in templates @click = "Addaction" >+</button> <button @cl ick= "Reduceaction" >-</button> </p> Transform Our methods method, first or the extension operator to Mapmutations and MapAction s join methods:{... mapmutations ([' Add ', ' reduce ']), ... mapactions                    ([' Addaction ', ' reduceaction '])}                Import our mapactions to use import {mapstate,mapmutations,mapgetters,mapactions} from ' Vuex '; To increase the asynchronous function of the async test demo actions, we add a timer (SetTimeOut) to defer execution SetTimeOut (() =>{context.commit (reduce)}                , 3000); Console.log (' I'm ahead of reduce ');

6.module Module Group (State Manager Module group operation)

As the complexity of the project increases and we share more and more of the state, we need to group the various operations of our state into groups and then write them by group. Declaring a module group: Declaring a module group in Vuex/store.js, or declaring a module group with our const constant method. The code is as follows: Const MODULEA = {state: {...}, mutations: {...}, action            S: {...}, getters: {...}  } Const MODULEB = {state: {...}, mutations: {...}, actions: {            ... }                    After declaring it, we need to change the value in the original Vuex.stroe: Const store = new Vuex.store ({modules: { A:modulea, B:moduleb}}) Store.state.a///-Modulea The status of store.state.b///-Moduleb is used in the template: Now we want to use the count state in the template, to write the 

  

 

Vuex-Centralized state management architecture specifically designed for Vue.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.