First we need to understand what vuex is, why vuex is used, and what is it used for?

Vuex is a centralized state management architecture designed specifically for Vue.js. State? I think of it as the part of the data where attributes need to be shared with other VUE components, called state. In simple terms, these are attributes that need to be shared in data.

  1. Use NPM package management tool to install VUEX. Type the following command on the control command line.

npm install vuex --save

2. Create a new store folder (this is not required) and create a new store.js file in the folder with our vue and vuex.

import Vue from 'vue';
import Vuex from 'vuex';
Copy the code

3. Use our vuex, and use vue.use for reference after introduction.

Vue.use(vue)
Vue.use(vuex)
Copy the code

With these three steps, the vuex reference is successful and we can have fun.

4. Import the new vuex file in main.js

import storeConfig from './vuex/store'
Copy the code

5. Then, add the Store object when instantiating the Vue object:

New Vue({el: '#app', router, store,// Use store template: '', components: {app}})Copy the code

Here's a Demo

1. Now we add a constant object to the store.js file. The store.js file is the one we used when we introduced vuex.

const state = {
 count:1
}
Copy the code

2. Use export Default to encapsulate the code so that it can be referenced externally.

export default new Vuex.Store({
 state
});
Copy the code

3. Create a new vue template in the Components folder named count.vue. In the template we introduce the store.js file we just created, and print the count value in the template with {{$store.state.count}}.

<template>
    <div>{{$store.state.count}}</div>
</template>
<script>
import store from '@/vuex/store'
 export default{
  data(){
   return{
    msg:'Hello Vuex',
   }
  },
  store
 }
</script>
Copy the code

4. Add two methods to change state in the store.js file.

const mutations={ add(state){ state.count+=1; }, reduce(state){ state.count-=1; }}Copy the code

Mutations here are fixed, meaning changed, so you don’t have to worry about it, all you know is that the way we want to change the value of state must be written in mutations.

5. Add two buttons in the count. Vue template, and call the method in mutations.

<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
Copy the code

This preview will allow you to add or subtract the count in vuex.

State Accesses the state object

Const State, which is what we call the access state object, is the shared value in our SPA (single-page application). The learning state object is assigned to the internal object, that is, the value in stroe.js is assigned to the value in our template data. There are three ways to assign

1. Assign a value to the computed attribute

For the computed property, the value in data can be changed before output, so we assigned the state value in store.js to the data value in our template.

computed:{ count(){ return this.$store.state.count; }}Copy the code

Return this.store.state. Count: return this.store.state. Count: return this.store.state. Make sure you write this, or you won’t find the store. That’s a pretty easy way to write it, but it’s a little tricky to write it, so let’s look at the second way.

2. Assign values via the object of mapState

So the first thing we’re going to do is import mapState.

import {mapState} from 'vuex';
Copy the code

Then write the following code in the computed properties:

Computed :mapState({count:state=>state.count // Interpret this as an incoming state object, modify the state.count attribute})Copy the code

3. Assign values via an array of mapStates

computed:mapState(["count"])
Copy the code

This is the simplest way to write it and is often used in real projects.

Mutations modify state ($store.com MIT ())Copy the code

Vuex provides the commit method to modify the state. Let’s paste the sample code content of the Demo and briefly review the modification method we used on the Button.

<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
Copy the code

Store. Js file:

const mutations={ add(state){ state.count+=1; }, reduce(state){ state.count-=1; }}Copy the code

Pass value: This is just a simple operation to change the state, in real projects we often need to pass value when changing the state. For example, in the previous example, we only added one at a time, and now we’re going to add by the values passed. In fact, we just need to add another parameter to Mutations and deliver it at commit. Let’s look at the code:

Now add n to the add method in the store.js file.

const mutations={ add(state,n){ state.count+=n; }, reduce(state){ state.count-=1; }}Copy the code

To modify the argument passed by the button’s commit() method in count.vue, we pass 10, which means we add 10 each time.

<button @click="$store.commit('add',10)">+</button>
<button @click="$store.commit('reduce')">-</button>
Copy the code

Template acquisition method Mutations

In actual development we don’t like to see methods like $store.com MIT (), we want to call them the same way we call methods in the template. For example, @click= “reduce” would be the same as the vuex plugin without reference. To do this, just two simple things are needed:

1. Import our mapMutations in template Count. Vue:

import { mapState,mapMutations } from 'vuex';
Copy the code

2, add methods attribute in the <\script> tag of the template, and add mapMutations

methods:mapMutations([
  'add','reduce'
]),
Copy the code

With the previous two, we are ready to use our Reduce or add methods directly in the template, as shown below.

<button @click="reduce">-</button>
Copy the code

Getters calculates filtering operations

Getters from the surface means to get. It can be regarded as a kind of re-editing before getting the data, which is equivalent to a filter and processing of the data. You can think of it as a calculated property of store.js.

Getters:

For example, we are now going to do an operation that evaluates the count property in the store.js file by adding 100 to it before it is printed. We first declare our getters property as const in store.js.

const getters = { count:function(state){ return state.count +=100; }}Copy the code

After we’ve written the gettters, we still need to introduce them in vuex.Store (), because we’ve introduced state and mutations before, so there are three introduction properties in the introduction. The code is as follows,

export default new Vuex.Store({
 state,mutations,getters
})
Copy the code

Now that the configuration is complete in store.js, we need to go to the template page to configure computed. There can only be one computed property in the vUE constructor. If you write more than one, only the last computed property is available, so make a change to the computed property that you wrote last time. We use the ES6 expansion operator “… .

computed:{
 ...mapState(["count"]),
 count(){
  return this.$store.getters.count;
 }
},
Copy the code

Note that when you write this configuration, every time the count value changes, it will add 100.

Use mapGetters to simplify template writing

We know that State and Mutations both have map references that simplify the code in our template, and we also have Getters, so let’s take a look at the code.

First, import our mapGetters with import

import { mapState,mapMutations,mapGetters } from 'vuex';
Copy the code

For computed, add mapGetters

. mapGetters(["count"])Copy the code

Actions Changes the status asynchronously

Actions have basically the same function as Mutations, except that actions asynchronously change the state state, Mutations synchronously change the state. I’m not going to go into a lot of detail about what asynchronous is and what synchronous is, but if you don’t know, just look it up on Baidu.

Declare actions in store.js

Actions can call the methods in Mutations, so we’re going to continue with the code that we did last time, and we’re going to call the add and Reduce methods in Actions.

const actions ={
 addAction(context){
  context.commit('add',10)
 },
 reduceAction({commit}){
  commit('reduce')
 }
}
Copy the code

We’ve got two methods in actions, addAction and reduceAction, and in the body of the method, we’re both calling the method inside Mutations with commit. If you’re careful, you’ll notice that the two methods also pass different parameters.

• OnText: The context object, which you can understand here as the store itself.

•{commit} : Pass the commit object directly to make the method body logic and code clearer.

Use in templates

We need to write code in the count.vue template for the actions to take effect. Let’s copy the two old buttons and change them to the method names in our Actions: addAction and reduceAction.

<button @click="addAction"">+</button>
<button @click="reduceAction">-</button>
Copy the code

To transform our methods, we first add mapMutations and mapActions using extension operators.

methods:{ ... mapMutations([ 'add','reduce' ]), ... mapActions(['addAction','reduceAction']) },Copy the code

You also need to remember to import our mapActions in order to use them.

Add asynchronous check

The results we’re looking at are exactly the same as what we’ve done with Mutations, and some partners will certainly wonder, what’s the use of actions, because to demonstrate the asynchronous functionality of actions, we’re adding a setTimeOut to delay execution. Use setTimeOut in addAction to delay execution.

setTimeOut(()=>{context.commit(reduce)},3000); Console. log(' I execute before Reduce ');Copy the code

We can see that ‘I execute ahead of Reduce’ is printed on the console first.

The module module group

As the complexity of the project increases and we share more and more states, we need to group the various operations of our states and then write them as groups. Today we will learn about Module: the group operations of a state manager.

Declare a module group:

To declare a group of modules in vuex/store.js, we still declare a group of modules using our const const method. The code is as follows:

const moduleA={
  state,mutations,getters,actions
}
Copy the code

Once declared, we need to change the original vuex.stroe value:

export default new Vuex.Store({
  modules:{a:moduleA}
})
Copy the code

Used in templates

Now we’re going to use the count state in the template, and we’re going to write it as an interpolation.

<div>{{$store.state.a.count}}</div>
Copy the code

So if we want to do it the easy way, we have to rutrun our state in our computed property. It is written as follows:

computed:{ count(){ return this.$store.state.a.count; }},Copy the code

So that’s how vuex works? Vuex use steps detailed, slightly inadequate, please comment points out, thank you!