Vuex preliminary understanding

Source: Internet
Author: User

Vuex preliminary understanding

Vuex is a state management mode of one-way data stream in vue. It can centrally store and manage the statuses of all components in an application, and has a set of rules to predict data changes. Similarly, there are status management modes such as redux and dva in react.

Generally, our status management includes the following parts:

  • State: this is the data source driving page changes
  • View state data display view
  • Response to changes in user operation data at the view layer

Data Streams in vue are unidirectional data streams.

One-way data flow is difficult to maintain when a sibling component needs to pass parameters or multiple components need to use the same State and multiple groups can change this state.

Therefore, what we adopt is to extract multiple shared States from a global Singleton (in fact, to separate the component states for management). In fact, in redux and dva, is to extract the status of each component to its own Singleton state, and these Singleton states are interconnected.

A rough flow of data streams in vuex is that we can view the layer and change the corresponding state in mutataions by triggering an action to mutations, then the state changes will affect the html structure of the corresponding view layer.

Of course, just like other state machine models, if you do not plan to develop large single-page applications, you do not need to use vuex.

Core concepts

The core of a vuex application is store. store contains most of the states in our application. The vuex status store responds quickly. When the state in the store changes, the corresponding components are also updated quickly. In addition, we need to follow the rules in vuex and cannot directly change the state. The only way to change the state in the store is through commit.

Through the information contained in each commit, we can easily and clearly see our intention to change the state each time, so that we can track data in the future.

State

Because vuex uses a single status tree, that is, you can put all the states in an application in this store. However, if you place too many states, this is also quite tricky, isn't it? I have not seen how vuex distributes status and status change events to various submodules.

MapState is an auxiliary function provided by vuex to simplify data access. mapState returns an object. Generally, we need to use a tool function to merge multiple objects into one, so that we can pass the final object to the computed attribute.

Of course, using vuex does not mean that we put all the states into vuex, although putting all the states into vuex will make the status changes more visible and easy to debug, however, if we put all our code in the global Store, it will become lengthy and inintuitive, so we still need to develop and weigh these items.

Getter

Sometimes we need to generate some States from the state in the store, such as filtering the list and counting:

Computed :{
DoneTodosCount (){
Return this. $ store. state. todos. filter (todo => todo. done). length
}
}

Vuex allows us to define "getter" in store ". just like the calculation attribute, the getter return value will be cached based on its dependency, and will be recalculated only when its dependency value changes.

Getter accepts state as its first parameter:

Const store = new Vuex. Store ({
State :{
Todos :[
{Id: 1, text: '...', done: true },
{Id: 2, text: '...', done: false}
]
},
Getters :{
DoneTodos: state => {
Return state. todos. filter (todo => todo. done)
}
}
})

Getter exposes the store. getters object:
Getter is similar to reducer in dva.

Store. getters. doneTodos //-> [{id: 1, text: '...', done: true} getter can also accept other getters as the second parameter:

Getters :{
//...
DoneTodosCount: (state, getters) => {
Return getters. doneTodos. length
}
}
Store. getters. doneTodosCount //-> 1

We can easily call it in any component:

Computed :{
DoneTodosCount (){
Return this. $ store. getters. doneTodosCount
}
}

MapGetters auxiliary functions

The mapGetters helper function only maps the getter in the store to the partial computing attribute.
For example:

Computed :{
... MapGetters (['getter1', 'getter2'])
}

According to the above writing, the getter1 and getter2 functions in global store can be used in local components.
If you want to take another name for a getter attribute, use the object format:

Computed :{
... MapGetters ({
NewGetter: "oldStoreGetter"
})
}

Mutation

The only way to change the status in the Vuex store is to submit mutation. mutation in Vuex is very similar to an event, which is somewhat similar to effects in dva. Each mutation has a string event type and a callback function. This callback function is where we actually change the status. And it will accept the state as the first parameter:

Mutations :{
SetAdminInfo (state, adminInfo ){
State. adminInfo = adminInfo;
},
SetCityList (state, cityList ){
State. cityList = cityList
}
}

Of course, we cannot directly call mutation handler. to execute this function, we need to call the store. commit method with the corresponding type:

When we need to pass parameters to mutation, we need to use payload. In the above example, adminInfo is the parameter we want to pass, which is called payload in vuex. Of course, the official recommendation is that payload should be an object as much as possible, so that we can better track data streams during use.

Of course, the better way to call mutation is to commit the object containing the type attribute:

Store. commit ({
Type: 'updateadmininfo ',
AdminInfo :{
Username: 'allen ',
Password: 'qwe123 ',
}
})

Mutation must comply with vue response rules

Since the status in the Vuex store is responsive, when we change the status, the vue component that monitors the status will be automatically updated. This means that mutation in Vuex also needs to follow the same precautions as Vue:

  • Initialize all attributes in the store.
  • Replace the old Object with the new Object, that is, a new state Object is returned each time. You can use Object. Assign.

Replace the Mutation event type with always-on

Using constants to replace mutation event types is a common mode in various flux implementations. The data flow of our entire project can be clearly viewed.

Of course, mutation must be a synchronous function. When we debug an app and observe the mutation log of devtool, each mutation is recorded, you must capture the snapshots in the previous and later statuses.

We can use this. $ store. commit ("example") in the component to submit mutation, or use the mapMutations helper function to map the methods in the component to the store. commit call.

Import {mapMutations} from 'vuex'

Export default {
//...
Methods :{
... MapMutations ([
'Credentials', // map 'this. increment () 'to 'this. $ store. commit ('credentials ')'

// 'Mapmutations 'also supports the following loads:
'Crementby' // map 'this. incrementBy (amount) 'to 'this. $ store. commit ('crementby', amount )'
]),
... MapMutations ({
Add: 'credentials' // map 'this. add () 'to 'this. $ store. commit ('credentials ')'
})
}
}

Action

Action is similar to mutation. The difference is:

  • Action submits mutation instead of directly changing the status.
  • Action can include any asynchronous operation.

Here is an example of a simple action:

Jsconst store = new Vuex. store ({state: {count: 0}, mutations: {increment (state) {state. count ++ }}, actions: {increment (context) {context. commit ('credentials') }}) const store = new Vuex. store ({state: {count: 0}, mutations: {increment (state) {state. count ++ }}, actions: {increment (context) {context. commit ('credentials ')}}})

Action is triggered using the store. dispatch method:

Store. dispatch ('credentials ');

You can use action to trigger mutation without the constraints that must be executed simultaneously. We can perform asynchronous operations within the Action.

You can also use payload to PASS Parameters in the same Action.

Store. dispatch ({
Type: "increment ",
Amount: 10
})

At the same time, actions are usually asynchronous. store. dispatch can process the Promise returned by the processing function of the triggered Action, and store. dispatch still returns Promise.

Now, we don't need to execute the promise. then function. We can simply use async/await.

Async action1 ({commit }){
Commit ('gotdata', await getData ());
}

Module

When a single State Tree is used, all states of an application are concentrated in a large object. When the application becomes very complex, the store object becomes very bloated.

Vuex allows us to split store into modules. Each module has its own state, mutation, acion, getter, and even nested submodules, which are separated from top to bottom.

Const moduleA = {
State :{...},
Mutations :{...},
Actions :{...},
Getters :{...}
}

Const moduleB = {
State :{...},
Mutations :{...},
Actions :{...}
}

Const store = new Vuex. Store ({
Modules :{
A: moduleA,
B: moduleB
}
})

Store. state. a //-> moduleA status
Store. state. B //-> moduleB status

Module local status

For mutation and getter in the module, the first parameter accepted is the partial state object of the module. Similarly, for actions within the module, the local state is exposed through context. state, and the root node state is context. rootState;

For the getter in the module, the root node status is exposed as the third parameter;

Namespace

By default, the action, mutation, and getter in the module are registered and then global namespace -- this allows multiple modules to respond to the same mutation or action.

Of course, in modularization, we can use namespaced: true to make it a namespace module. After a module is registered, all its getter, Action, and mutation parameters are automatically renamed Based on the path registered by the module. After namespace is enabled, a whole store is divided into modules.

Dynamic module Registration

After creating a store, you can use the store. registerModule method to register a module:

// Register the module 'mymodule'
Store. registerModule ('mymodule ',{
//...
})
// Register the nested module 'nested/mymodule'
Store. registerModule (['nested ', 'mymodule'], {
//...
})

Of course, we can also dynamically uninstall the module through store. unregisterModule (moduleName. However, we cannot use this method to uninstall static modules.

Vuex does not limit your code structure. However, he defines some rules that need to be followed:

  • Application-level statuses should be concentrated in a single store object.
  • Submitting mutation is the only way to change the status, and this process is synchronized.
  • Asynchronous logic should be encapsulated in Action.

This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151498.htm

Related Article

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.