Introduction to the

Hello, Hellow, everyone, I haven’t seen you for a week. This week, I want to talk about the use of Vuex method, which is not as simple as state and mutations. You can regard this as an entry-level teaching.

Understand Vuex modules

Some of you might have asked me what modules are for Vuex, and I’m going to talk about modules. As you get bigger and bigger, a single store file is definitely not what you want, so that’s where the concept of modularity comes in. First let’s look at how to use modules.

Install Vuex

npm install vuex --save
cnpm install vuex --save
Copy the code

Create stroe file and create a new index.js file

// Import vue and vuex import vue from'vue'
import Vuex from 'vuex'Vue.use(Vuex) {vue.use (Vuex) {vue.use (Vuex)exportModules: {people_vuex: People_vuex}} default new vuex. Store({// Vuex :people_vuex}});Copy the code

So a simple module is loaded, and we’ve added the People_vuex module to modules

Other methods are introduced and used after Vuex modules is introduced

Vuex Modules should be introduced at least in state. Now let’s see how to introduce state

Before introducing state, create a new JS file called People_vuex.js and then introduce the js file in index.js

// Import vue and vuex import vue from'vue'
import Vuex from 'vuex'// Import people_vuex from people_vuex'./people_vuex'Vue.use(Vuex) {vue.use (Vuex) {vue.use (Vuex)exportModules: {people_vuex: People_vuex}} Default new Vuex.Store({people_vuex: People_vuex}})Copy the code

Create a people_state.js file, but first complete the contents of People_vuex.js.

import people_state from './people_state'
export default {
    state:people_state,
}
Copy the code

So here we see people_vuex.js importing the state module people_state.js, so you get a sense of what I’m talking about here, People_vuex is introduced to people_vuex via modules, and people_vuex.js is people_vuex. A separate module is created, which we’ll cover next, but we’ll add state first.

People_state.js

const people_state={
    name:'hellow'} / / useexportDefault encapsulation, so that external accessexport default people_state;
Copy the code

The next global import Vuex entry file is in main.js.

// reference vuex file entry import store from'./store/index'

new Vue({
    ...
        store:store,
    ...
})
Copy the code

Then create a new a.value and write it like this

<template>
    <div>
      {{getCoin}}
    </div>
</template>

<script>
export default {
    ...
        computed:{
            getCoin() {return this.$store.state.people_vuex.coin } } ... },created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>
Copy the code

This.$store () {return ();}} this.$store () {return ();}} By the way, I printed the data we collected below for convenience. You can run and see.

Next, we will talk about mutations. There has been a brief introduction of the use of mutations in our article before. If you are interested, you can go and have a look, but this time it is slightly different.

How to use Vuex together with Busemit

Start by creating People_articles.js in the Store folder

import people_state from './people_state'
const people_mutations={
    updateCoin (people_state) {
            people_state.coin = 'newName'}}export default people_mutations;
Copy the code

Then refer to people_mutations. Js in People_vuex.js

import people_state from './people_state'
import people_mutations from './people_mutations'
export default {
    state:people_state,
    mutations:people_mutations
}
Copy the code

The third step is to use it in the vue file in the a.vue file

<template>
    <div>
      {{getCoin}}
      <button v-on:click="changeCoin()"</button> </div> </template> <script>export default {
    ...
        computed:{
            getCoin() {return this.$store.state.people_vuex.coin
            }
        },
        methods:{
            changeCoin () {
                this.$store.commit('updateCoin'); }}... },created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>
Copy the code

So you can see what happens.

To the chase

After saying so much, you must wonder why I just start the topic now. Because this is the primary use of Vuex, I should talk about it in detail in front, in case beginners don’t know the first steps, then we can’t talk about the back. All right, let’s cut to the chase.

First of all, let’s take a demo as an example. As I am a financial blockchain expert, I have a lot of contact with currencies, such as Bitcoin, litecoin, ether and so on, but there is no common unit between them. For example, bitcoin 1 is equivalent to 100 million cong. For example, the unit of Ether coin is 1 litecoin equals 1e18Wei, which is followed by 18 zeros. Then, if you are interested, you can learn about it. Next, you can enter the part of simulation requirement. This display amount at the time of transfer and the back-end data sent to the back-end of course again this before or need to change the value in order to we can see clearly, so our thinking is the first receive the backend data, after data processing, and then put it on the page show, after that there will be a change of values, Finally, the value is sent asynchronously to the back end, and the whole process is complete.

The first step is to review what we did above, but with a few minor changes, and I’ll comment it in the code below, so watch out.

// vue and vuex import vue from'vue'
import Vuex from 'vuex'Vue.use(Vuex) {vue.use (Vuex) {vue.use (Vuex)exportModules: {people_vuex: People_vuex}} default new vuex. Store({// Vuex :people_vuex}});Copy the code
// People_state.js will add getters data handling and actions asynchronous submission methods import People_state from'./people_state'
import people_mutations from './people_mutations'
export default {
    state:people_state,
    mutations:people_mutations
}
Copy the code
Const people_state={coin:' '} / / useexportDefault encapsulation, so that external accessexport default people_state;
Copy the code
// People_roads.js is an important note to note: import people_state from'./people_state'Const People_mutations ={// updateCoin (People_state) {people_state.coin ='1000000100000100001000100101'}, // Pay attention to mutations, there are two values that can be passed in. Pay attention to the front value, and we don't care about the back value, which is what is returned from the back end. ChangeCoin (people_state,coin){people_state.coin = coin}};export default people_mutations;
Copy the code
<template> <div> {{getCoin}} <button V-on :click="changeCoin()"</button> </div> </template> <script>export default {
    ...
        computed:{
            getCoin() {return this.$store.state.people_vuex.coin
            }
        },
        methods:{
            changeCoin () {
                this.$store.commit('updateCoin'); }}, // Note that here we simulate the value passed in by the back end. The second parameter in commit is the value passed in by the back endinitializeCoin () {
          this.$store.commit('changeCoin'.'1001000100001000001000001'); },created(){ this.initializeCoin(); }... },created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>
Copy the code

Now that we’ve done our preparatory work, let’s use getters to process the data. First, create new people_getters.js

import people_state from './people_state'
const people_getters={
    
}
export default people_getters
Copy the code

Before about some data processing, the first is getters method we can as a secondary processing of data, how to deal with after we get the data is random, but inside a processing method of handling is fixed, such as I want to handle COINS to comma separated now, so this method can only deal with the similar things, But is the getters gave us another option is in the secondary processing the data again to add a method after the three times in the data processing, but more to go into here, method is also introduced into two parameters, the second parameter is the secondary processed data before, paste a code you see below

// This function can be passed to the next getters for processing. Getters also get other getters as the second parameter XXXX: (a, b) => {return b.c.length
}
Copy the code

For reference only, the next thing I want to talk about is the use of getters in the simulation requirements. Without further ado, look at the code.

Introduce People_getters.js in People_vuex.js

import people_state from './people_state'
import people_mutations from './people_mutations'
import people_getters from './people_getters'
export default {
    state:people_state,
    mutations:people_mutations,
    getters:people_getters
}
Copy the code

The second step is to write a data processing method, that is, we talk about the amount of comma interval.

import people_state from './people_state'Const People_getters ={getReverseCoin: people_state => {const People_getters ={getReverseCoin: People_state =>if(people_state.coin)
        {
            people_state.coin = people_state.coin.toString().replace(/\$|\,/g,' ');
            if(' '==people_state.coin || isNaN(people_state.coin)){return 'Not a Number ! '; } var sign = people_state.coin.indexOf("-")> 0 ? The '-' : ' ';
            var cents = people_state.coin.indexOf(".")> 0 ? people_state.coin.substr(people_state.coin.indexOf(".")) : ' ';
            cents = cents.length>1 ? cents : ' ' ;
            people_state.coin = people_state.coin.indexOf(".") > 0? people_state.coin.substring(0,(people_state.coin.indexOf("."))) : people_state.coin ;
            if(' ' == cents){ if(people_state.coin.length>1 && '0'= = people_state. Coin. Substr (0, 1)) {return 'Not a Number ! '; }}else{if(people_state.coin.length>1 && '0'= = people_state. Coin. Substr (0, 1)) {return 'Not a Number ! '; }}for (var i = 0; i < Math.floor((people_state.coin.length-(1+i))/3); i++)
            {
                people_state.coin = people_state.coin.substring(0,people_state.coin.length-(4*i+3))+', '+people_state.coin.substring(people_state.coin.length-(4*i+3));
            }
            return(sign + people_state.coin + cents); } // Note that you mustreturnOtherwise, an error will be reported. Here is the processed datareturn people_state.coin
    },
};
export default people_getters
Copy the code

Let’s look at how to use the getters method, and I’ll mark the changes below.

<template>
    <div>
      {{getCoin}}
      <button v-on:click="changeCoin()"</button> </div> </template> <script>export default {
    ...
        computed:{
            getCoin(){// This is where the change is used$store.getters takes the getReverseCoin method we just definedreturn this.$store.getters.getReverseCoin
            }
        },
        methods:{
            changeCoin () {
                this.$store.commit('updateCoin'); // The results of the treatment will be visible if you print them out here, even if you change the values using the mutations method, console.log(this) will be processed.$store.getters.getReverseCoin); }},initializeCoin () {
          this.$store.commit('changeCoin'.'1001000100001000001000001'); },created(){ this.initializeCoin(); }... },created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>
Copy the code

As mentioned above, getters can pass in two parameters, and the second parameter is the previously processed data to be processed three times again. However, here is the usage method, which will not be written in such detail. If you are interested, you can go to the official document.

Vuex Getter official document

Getters: {// The method here is to process the second argument and then throw it. I won't go into details here.doneTodosCount: (state, xxxx) => {
    return xxxx.a.length
  }
}
Copy the code

Now that we’re done with the previous steps, it’s time to move on to the final step, which is the Actions asynchronous method.

The Action commits mutation rather than a direct state change.

Actions can contain any asynchronous operation.

Actions can contain any asynchronous operation, including asynchronous requests, etc. We will not talk about the use of asynchronous requests, but also can be understood in the Action of a request method, so that no more talk, directly on the code.

We’ll start with a new people_actions.js file, and notice the comments below

/ / here of other ways to use a slightly different, here introduces two js is a have been introduced into people_state. Js, another is people_mutations js, this is what I want to simulate method, after the change in the state of numerical can request directly. import people_mutations from'./people_mutations'
import people_state from './people_state'Open mutations const People_Actions ={updateCoinSubmit ({commit}) {setTimeout(() => {// The method used here is the same as the method in the vue file, except that there are not so many reference prefixes. You can call the method in mutations directly using commit. commit('updateCoin') // The value is not processed and can be directly returned to the back end if it meets the conditions described before. console.log(people_state.coin) }, 1000) } };export default people_actions
Copy the code

Then reference it in people_vuex.js

import people_state from './people_state'
import people_mutations from './people_mutations'
import people_getters from './people_getters'
import people_actions from './people_actions'
export default {
    state:people_state,
    mutations:people_mutations,
    getters:people_getters,
    actions:people_actions
}
Copy the code

I’ll just refer to it in my vue file, and I want you to pay attention to my comments here. It’s not that big of a change, but I want you to pay attention to it. Here’s the code.

<template>
    <div>
      {{getCoin}}
      <button v-on:click="changeCoin()"</button> </div> </template> <script>export default {
    ...
        computed:{
            getCoin() {return this.$store.getters.getReverseCoin
            }
        },
        methods:{
            changeCoinMutations can be invoked using commit, while mutations can only be invoked using dispatch. Therefore, everyone should pay attention to it. this.$store.dispatch('updateCoinSubmit');
                console.log(this.$store.getters.getReverseCoin); }},initializeCoin () {
          this.$store.commit('changeCoin'.'1001000100001000001000001'); },created(){ this.initializeCoin(); }... },created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>
Copy the code

In fact, there is also a distribution Action triggered by store.dispatch, which will not be discussed here. If you are also interested in Vuex, you can go to the official website. Next week I’ll take you a little deeper into Vuex and understand more about it.

The following is the entire code of this period, posted out for you to understand.

//a.vue
export default {
    ...
        computed:{
            getCoin() {return this.$store.getters.getReverseCoin
            }
        },
        methods:{
            changeCoin () {
                this.$store.dispatch('updateCoinSubmit');
                console.log(this.$store.getters.getReverseCoin); }},initializeCoin () {
          this.$store.commit('changeCoin'.'1001000100001000001000001'); },created(){ this.initializeCoin(); }... },created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>
Copy the code
//main.js
import store from './store/index'

new Vue({
    ...
        store:store,
    ...
})
Copy the code
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import people_vuex from './people_vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    modules: {
        people_vuex:people_vuex
    }
})
Copy the code
//people_vuex.js
import people_state from './people_state'
import people_mutations from './people_mutations'
import people_getters from './people_getters'
import people_actions from './people_actions'
export default {
    state:people_state,
    mutations:people_mutations,
    getters:people_getters,
    actions:people_actions
}
Copy the code
//people_state.js
const people_state={
    coin: ' '
};
export default people_state;
Copy the code
//people_mutations.js
import people_state from './people_state'
const people_mutations={
    updateCoin (people_state) {
        people_state.coin = '1000000100000100001000100101'
    },
    changeCoin (people_state,coin){
        people_state.coin = coin
    }
};
export default people_mutations;
Copy the code
//people_getters.js
import people_state from './people_state'
const people_getters={
    getReverseCoin: people_state => {
        if(people_state.coin)
        {
            people_state.coin = people_state.coin.toString().replace(/\$|\,/g,' ');
            if(' '==people_state.coin || isNaN(people_state.coin)){return 'Not a Number ! '; } var sign = people_state.coin.indexOf("-")> 0 ? The '-' : ' ';
            var cents = people_state.coin.indexOf(".")> 0 ? people_state.coin.substr(people_state.coin.indexOf(".")) : ' ';
            cents = cents.length>1 ? cents : ' ' ;
            people_state.coin = people_state.coin.indexOf(".") > 0? people_state.coin.substring(0,(people_state.coin.indexOf("."))) : people_state.coin ;
            if(' ' == cents){ if(people_state.coin.length>1 && '0'= = people_state. Coin. Substr (0, 1)) {return 'Not a Number ! '; }}else{if(people_state.coin.length>1 && '0'= = people_state. Coin. Substr (0, 1)) {return 'Not a Number ! '; }}for (var i = 0; i < Math.floor((people_state.coin.length-(1+i))/3); i++)
            {
                people_state.coin = people_state.coin.substring(0,people_state.coin.length-(4*i+3))+', '+people_state.coin.substring(people_state.coin.length-(4*i+3));
            }
            return (sign + people_state.coin + cents);
        }
        return people_state.coin
    },
};
export default people_getters
Copy the code
//people_actions.js
import people_mutations from './people_mutations'
import people_state from './people_state'
const people_actions={
    updateCoinSubmit ({ commit }) {
        setTimeout(() => {
            commit('updateCoin')
            console.log(people_state.coin)
        }, 1000)
    }
};
export default people_actions
Copy the code

Finally, the other article directories used for reference before writing this article.

Vuex website

Vuex is super easy, just 3 steps

Vuex is super easy, just 3 steps

JS- Adds a thousandth comma separator for the amount

Afterword.

This text articles though some repetitive, but I still hope you can see here, I want to say is that the couple can see introduction to this article, and the old people can review, in fact, knowledge is endless, we are looking for knowledge at the same time should not be your before leave or stop learning, the three provinces in my body, this is what I want to say, thank you for watching, see you next week.