First Knowledge Vue 2.0 (8): Vuex Advanced

Source: Internet
Author: User

The main content is three parts:

    1. Vuex Modular
    2. Vuex namespaces
    3. Mutations and actions

Modular

Because a single state tree is used, all states of an application are concentrated on a larger object, and the store object can become quite bloated when the application becomes very complex.

To solve these problems, Vuex allows us to split the store into modules, each with its own state, mutation, action, getter.

Therefore, create a store directory to store the state.

Store/|_ index.js|_ hellomodule.js|_ Gamemodule.js

Export components in index.js and register in Main.js
Index.js

/**/'./hellomodule.js './gamemodule.js' = {    modules: {        Hellostate,        gamestate    }}

Main.js

//  ... Import {modules} from './store 'vue.use (VUEX)// centralized state management new  Vuex.store (modules ); New Vue ({  ' #app ',  store,// I'm here  Template: ' <App/> ' , Components  : {App}})

Name space

Before a namespace appears, the module simply separates states, mutations or actions, but not separate. At the time of invocation, if the same name is used, it will be executed at the time of invocation.

As a result, the method names in mutations or actions are generally abstracted into constants and stored in separate files to avoid naming pollution.

With a namespace, as long as the namespaced:true is set up, the methods between the modules are independent of each other, and the syntax is slightly modified.

Hellomodule.js

/*Global Module:true*/Exportdefaultmodule = {    //Open Namespacenamespaced:true,    //Define StateState : {msg:' I am the Hello module '    },    //Get Statusgetters: {msg: (state)= = (TXT) = {            returnTXT + state.msg//Accept the reference        }    },    //Change Statemutations: {//contains the asynchronous modification statesetmsg (State, msg) {state.msg=msg setTimeout (()={state.msg= ' Mutations modified successfully '//use commit to call this asynchronous method directly, can achieve the purpose of modifying data, the final state is not able to trace}, 1000)        },        //does not contain an asynchronous modification statesetMsg2 (State, msg) {state.msg=msg}}, actions: {//Modify State asynchronouslysetmsg (Context, msg) {Context.commit (' SETMSG2 ', msg) setTimeout (()={context.commit (' SetMsg2 ', ' actions modified successfully ')//This asynchronous state modification can be traced using the dispatch call}, 1000)        }    }}

Gamemodule.js slightly

Mutations and actions

Why is it that mutation can only be synchronized, and the action executes mutation asynchronously through commit?

Website Explanation:

Now imagine that we are debugging an app and observing the mutation log in Devtool. Each mutation is recorded and devtools needs to capture a snapshot of the previous state and the latter state. However, in the example above, the callback in the Async function in mutation makes this impossible: because when mutation is triggered, the callback function is not yet called, Devtools does not know when the callback function is actually called-- Essentially any change in the state that is made in the callback function is not traceable.

Mixing asynchronous calls in mutation can cause your program to be difficult to debug. For example, when you call two mutation that contain an asynchronous callback to change the state, how do you know when the callback and which callback first? That's why we have to differentiate between these two concepts. In Vuex, mutation are synchronous transactions.

In other words, the method that uses commit to call mutations, contains the asynchronous modification state operation, also can execute successfully;

However, during the debug process, Devtools can not capture the snapshot of the state of the asynchronous modification, which makes debugging difficult;

As a result, the official dispatch calls the actions method to complete the asynchronous operation.

You can also use dispatch to return the Promise object and complete the then operation in the component.

Hello.vue

<Template><Divclass= "Hello">    <H2>{{msg}}</H2>    <Button@click= "Answer">Modify</Button>    <Button@click= "Show">View</Button></Div></Template><Script>Exportdefault{name:'Hello', data () {return{newmsg:"modified in"}}, computed: {msg:function () {            return  This. $store. State.helloState.msg}}, methods: {Answer () { This. $store. Dispatch ('hellostate/setmsg', This. newmsg); }, Show () {alert ( This. $store. getters['hellostate/msg']('View content is:')); }    }}</Script><style>. Hello{Background-color:#E1FFFF;}</style>

Helper functions for component bindings

That is mapstate,mapmutations,mapgetters, mapactions these, generally can be regarded as a simplified grammar of the grammatical sugar, have the opportunity to talk about in detail.
Use Mapstate to get a simple instance of the state:
Modify Hello.vue

Import {mapstate} from ' Vuex 'default  {    //  ...         computed: {             ... mapstate          ({= = state.helloState.msg        })    },}

First Knowledge Vue 2.0 (8): Vuex Advanced

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.