Vuex is actually super simple, just three steps

Source: Internet
Author: User
Preface

In the previous projects, there were more or less components that needed to communicate with each other. For various reasons,
The cost of event bus is higher than that of vuex, so vuex is selected for technology selection, but I don't know why,
Some new people in the team began to retreat when they heard about vuex, because vuex was very difficult? Is it really difficult?
Today, we use three simple steps to prove how simple vuex is.

This is purely personal experience, and it is inevitable that there are errors. If you find any problems, please correct them! This is an entry-level tutorial, entry-level tutorial, and entry-level tutorial for beginners.
Step 1

Create a new vue project and install vuex. We will not introduce it too much here. You can click here. By default, you have these skills ^_^

Step 1

Create.jsFile with any name and location. We recommend that you/src/storeDirectory (if not, create a new one)

File Location/src/store/index. js

// Introduce vue and vueximport vue from 'vue 'import vuex from 'vuex' // you need to use it here. Keep it in mind. use (vuex) // export the export default new vuex of a store instance directly. store ({// data state: {Name: 'oldname'} similar to Vue, // mothods (synchronous method) mutations: {updatename (state) {state. name = 'newname '}}})

The code looks a little bit more, but does it look familiar? It is not much different from a common vue.
This step is actually to create a new store, but we haven't used it in the project yet.

Step 2

Introduce the above file in the entry file, and slightly change the parameter passed to new vue,The added row is followed by a comment.

File Location/src/Main. js(The entry automatically generated by Vue-cli. If you don't need scaffolding, you don't need to explain it)

Import vue from 'vue 'import app from '. /APP 'import vuexstore from '. /store' // Add new vue ({El: '# app', store: vuexstore // Add components: {app}, template:' & lt; APP/& gt; '})
Tip: The address after import store from './store' is the location of the file we created above ( /src/store/index.js),
Because index. JS is used here, it can be omitted.
Step 3

The above two steps have actually completed the basic configuration of vuex, and the next step is to use

File Location/src/Main. js(This is also the app. vue generated by Vue-cli. To facilitate the demonstration, I will remove unnecessary code)

& Lt; Template & gt; & lt; Div & gt ;{{ getname }}& lt; button @ click = "changename" value = "renamed" & gt; rename & lt;/button & gt; & lt;/Div & gt; & lt;/template & gt; & lt; script & gt; export default {computed: {getname () {return this. $ store. state. name }}, Methods: {changename () {This. $ store. commit ('updatename ') }}& lt;/script & gt;

This is a very common vue file. The difference is that we need to use the computed attribute to obtainStore "data"

And if we want to change the data, we will not use it any more.this.xxx = xxxChange this. $ store. Commit ('updatename ')

Summary

What do you think is the significance of the above example? Why not use vue data and methods directly?

The above example is just to briefly explain how to use vuex, so it simplifies some processes. Imagine if you have such a page:
A total of 10 layers of components are nested (that is, there are child components in the child components, there are child components under the child components, and so on 10 layers)
Then the data of the last component changes. To notify the first component, we only needthis.$store.commit(),
Then, the outermost component can obtain the corresponding value with the computed attribute to implement real-time update without the need for layers of $ emit.

Last

I would like to extend the getter, Action + dispatch, modularity, and so on at the end, but in order to be worthy of this title,
I had to put it in the next article: vuex is actually super simple. There are three steps after completing the three steps.

Vuex is actually very simple. There are three steps after you finish the three steps.

The previous vuex is actually very simple, only three steps are required
I briefly introduced step 3 of vuex, but for beginners to easily digest it, I cut a lot of content. In this section, I will add the missing content,
If you have not read the previous article, stamp the link and read it first. Otherwise, you will feel confused.

This is purely personal experience, and it is inevitable that there are errors. If you find any problems, please correct them!

The same is true for beginners.

I, Getter

Let's first recall the previous code.

computed:{    getName(){      return this.$store.state.name    }}

Here we assume that the logic is changing, and the final expected data (getname) is based onthis.$store.state.name
After complex computing, the getname must be used in many places, so we have to copy several copies.

Vuex provides getter for us. Please refer to the Code (File Location/src/store/index. js)

Import vue from 'vue 'import vuex from 'vuex' vue. use (vuex) Export default new vuex. store ({// data state similar to vue: {Name: 'oldname'}, // Add getters: {getreversename: State = & gt; in the following five actions similar to vue computed; {return state. name. split (''). reverse (). join ('') }}, // similar to mothods (synchronous method) mutations in vue: {updatename (state) {state. name = 'newname '}}})

Then we can useFile Location/src/Main. js

computed:{    getName(){      return this.$store.getters.getReverseName    }}

In fact, Getter not only serves as an encapsulation, but also caches result data like the computed attribute of vue,
Re-calculation is required only when dependency changes.

II, Actions and $ dispatch

Careful, you must find that in my previous CodemutationsCommented onSimilar to mothods in vue (synchronous method)

Why?methodsWhat about the synchronization method? Mutation can only be a synchronous function. It can only be a synchronous function !!
See vuex's explanation:

Now imagine that we are debugging an app and observing the mutation log in devtool. Each mutation is recorded,
All devtools need to capture snapshots of the previous and next statuses. However, in the above example, the callback in the asynchronous function of mutation makes this
Possible completion: When mutation is triggered, the callback function is not called, and devtools does not know when the callback function is actually called.
Essentially, any state changes made in the callback function cannot be tracked.

So what if we want to trigger an asynchronous operation? The answer is: Action + $ dispatch. We will continue to modify the code below store/index. js.

File Location/src/store/index. js

Import vue from 'vue 'import vuex from 'vuex' vue. use (vuex) Export default new vuex. store ({// similar to data state: {Name: 'oldname'} of Vue, // similar to computed getters: {getreversename: State = & gt; {return state. name. split (''). reverse (). join ('') }}, // similar to mothods (synchronous method) mutations in vue: {updatename (state) {state. name = 'newname'}, // similar to mothods in vue (Asynchronous Method) -------- actions added for the following 7 actions: {updatenameasync ({commit}) {setTimeout (() = & gt; {commit ('updatename') }, 1000 )}}})

Then we can use this on our vue page.

methods: {    rename () {        this.$store.dispatch('updateNameAsync')    }}
III, Module Modularization

When the project is getting bigger and bigger, a single store file is definitely not what we want, so it is modularized.
Hypothesissrc/storeThe directory contains the two files.

moduleA.js

export default {    state: { ... },    getters: { ... },    mutations: { ... },    actions: { ... }}

moduleB.js

export default {    state: { ... },    getters: { ... },    mutations: { ... },    actions: { ... }}

Then we canindex.jsChange to this

import moduleA from './moduleA'import moduleB from './moduleB'export default new Vuex.Store({    modules: {        moduleA,        moduleB    }})

In this way, we can easily split a store into multiple.

IV, Summary
  1. The actions parameter isstoreObject, while the parameters of getters and mutations arestate.
  2. Actions and mutations can also pass the second parameter. For details, see the official vuex documentation.
  3. Getters/mutations/actions all have corresponding maps, such as mapgetters. For details, see the official vuex documentation.
  4. If there is a naming conflict in the module, you can use the namespace. For details, see the official vuex documentation.
  5. Vuex is actually very similar to Vue, with data (state), methods (mutations, actions), computed (getters), and modularity.

Vuex is actually super simple, just three steps

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.