What is VUex

Vuex is a state management mode developed specifically for vue.js applications

What is state management

A first look at one-way data flows helps us understand state management better. The simple VUE file we write usually contains data, template and methods. Data can be regarded as state respectively, the data source driving the application, that is, the defined variable. Template is a view that maps state to the view declaratively, showing variables; Methods are actions that respond to state changes on a view.

3. Why vuex

If we encounter multiple views that depend on the same state and behavior from different views that need to change the same state, this one-way data flow can also be implemented through component sibling/parent-child communication, but the code becomes complex and difficult to maintain. Therefore:

Extract the shared state of components and manage it in a global singleton mode. In this mode, our tree of components forms a large “view” where any component can obtain state or trigger behavior no matter where it is in the tree. Vuex removes the shared state from the project and places it in the Store folder. In this case, all vue templates in the project are views and the state in the store can be accessed through this.$store. To get the state you defined, which can be obtained by any VUE file, and can also change and trigger store behavior)

2. By defining and isolating concepts in state management and by enforcing rules to maintain independence between views and states, our code becomes more structured and maintainable. Vuex defines four attributes: State, getters, mutations and Actions. Different attributes do different things to maintain the independence of state, view and behavior.)

In simple terms, VUex uses a store object to hold all of the application-level state, which is where the data comes from. Of course, if the application is large, we can modularize the store, meaning that each module has its own store.

State, getter, mutation and Action state in VUEX: define variables. Getters: Get variables; Mutations: perform simultaneous operations on variables; Actions: Perform operations on variables asynchronously; MapState, mapGetters, mapActions, and mapMutations in VUEX are all auxiliary functions.

How to use state, getter, mutation, action in VUEX

1. After the introduction of mapState into VUEX, we need to define variables in state, similar to data in VUE, to store state through state.

For example, we define state in VUEX as:

import Vuex from 'vuex' Vue.use(Vuex); export default new Vuex.Store({ state: {// Store state, Data nickname:'qiqi', age:18, gender:'men', firstname:'a', lastname:'b', days:1000,}, getters:{}, mutations: {}, actions: {}, modules: {} })Copy the code

We want to use the nickname, age, and gender properties in the component. Initialization of props, methods, data, and computed is done between beforeCreated and created, so we use properties in computed.

When we do not use mapState, the Store instance is injected into all the children of the root component, which can be accessed through this.$store. The code is as follows:

The < div > < h1 > nicknamed: {{nickname}} < / h1 > < h1 > {{nickname}} age is: {{age}} < / h1 > < h1 > gender is: {{gender}}</h1> </div> </template> <script> export default { name: "Vhome", computed:{ nickname(){ return this.$store.state.nickname; }, age(){ return this.$store.state.age; }, gender(){ return this.$store.state.gender; } }, } </script>Copy the code

When a component needs to fetch multiple states, it can be repetitive and redundant to declare all those states as computed properties. To solve this problem, we can use the mapState helper function to help us generate calculated properties:

export default { name: "Vhome", computed:{ ... mapState(['nickname','age','gender']), // nickname(){ // return this.$store.state.nickname; // }, // age(){ // return this.$store.state.age; // }, // gender(){ // return this.$store.state.gender; / /}}}Copy the code

Remember: when using helper functions such as mapState, the preceding method name is the same as the name of the fetched property.

MapGetters Vuex allows us to define “getters” in stores (think of as computed properties of stores). Just like evaluating properties, the return value of a getter is cached based on its dependency and is recalculated only if its dependency value changes. Part of the vuEX code is as follows:

import Vuex from 'vuex' Vue.use(Vuex); export default new Vuex.Store({ state: {// Store state, Data nickname:'qiqi', age:18, gender:'men', firstName :'a', lastName :'b', days:1000,}, getters:{ realname(state){ return state.firstname+state.lastname }, days_us(state){ return (state.days/7).toFixed(2) } }, mutations: {}, actions: {}, modules: {} })Copy the code

The HTML part is:

< h1 > full name is: {{realname}} < / h1 > < h1 > weeks is: {{days_us}} < / h1 >Copy the code

When mapGetters are not used, the js part is:

computed:{ realname(){ return this.$store.getters.realname; }, days_us(){ return this.$store.getters.days_us; }},Copy the code

When using mapGetters, the js part is:

 import {mapGetters} from 'vuex'
 export default {
     name: "Vhome",
     computed:{
       // realname(){
       //     return this.$store.getters.realname;
       // },
       // days_us(){
       //     return this.$store.getters.days_us;
       // },
       ...mapGetters(['realname','days_us']),
   },
}
Copy the code

MapMutations the only way to change the state in the store of VUex is to submit mutation. Mutations in VUEX are very similar to events: each mutation has a string event type (type) and a callback function (handler). This callback is where we actually make the state change, and it accepts state as the first argument. For example, when we implement the requirement of clicking button age + 1, the vuEX code is as follows:

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); export default new Vuex.Store({ state: {// Store state, Data nickname:'qiqi', age:18, gender:'men', firstName :'a', lastName :'b', days:1000,}, getters:{ realname(state){ return state.firstname+state.lastname }, Days_us (state){return (state.days/7). ToFixed (2)}}, mutations: {// similar to methods addAge(state){state.age++; } }, actions: {}, modules: {} })Copy the code

Use this. Codestore.com MIT (‘ XXX ‘) to submit mutation when not using mapMutations. The HTML code is as follows:

<div><button @click="test"> use mutations age + 1</button></div>Copy the code

The js code is as follows:

methods:{
    test(){
        this.$store.commit('addAge')
    },
}
Copy the code

When using mapMutations, methods in the component are mapped to the store.mit call. The HTML code is as follows:

<div><button @click="addAge"> use mutations age + 1</button></div>Copy the code

The js code is as follows:

import {mapMutations} from 'vuex' export default { name: "Vhome", methods:{ // test(){ // this.$store.commit('addAge') // }, ... mapMutations(['addAge']), } }Copy the code

Remember: mutation must be a synchronization function

4, mapActions actions are similar to mutation, except that they commit mutations instead of directly changing the state. Actions can contain any asynchronous operation. For example, if we need to manipulate age, the vuEX code would look like this:

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); export default new Vuex.Store({ state: {// Store state, Data nickname:'qiqi', age:18, gender:'men', firstName :'a', lastName :'b', days:1000,}, getters:{ realname(state){ return state.firstname+state.lastname }, Days_us (state){return (state.days/7). ToFixed (2)}}, mutations: {// similar to methods addAge(state){state.age++; } }, actions: { addAgeAction({ commit }){ commit('addAge'); } }, modules: {} })Copy the code

When mapActions are not used, the Action is triggered by the store.dispatch method. The code is as follows:

</button></div> methods:{test1(){this.$store.dispatch('addAgeAction')}}Copy the code

When using mapActions, map a component’s methods to a store.dispatch call. The code is as follows:

<div>< button@click ="addAgeAction"> Use actions to add age 1</button></div> import {mapActions} from 'vuex' export default {name: "Vhome", methods:{ ... mapActions(['addAgeAction']), } }Copy the code

Mutation must be executed synchronously, so the Action is not bound! We can perform asynchronous operations within the Action.