Master Vuex in 5 minutes

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

What is Vuex?

Concept: Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.

To put it simply (in human language), this means that you can communicate with any component and detect changes in data.

Second, Vuex principle

Vuex is the Model layer concentrated in MVC pattern, which stipulates that all data operations must be carried out through the process of action-mutation – state, and then combined with the two-way binding features of Vue’s data view V-Moder to achieve page display update.

Let’s take a look at a picture to understand the process.

Brief details of main methods:

  • Vue Components: Vue Components. Display page, responsible for receiving user operations and other interactive behaviors, execute dispatch method to trigger corresponding action to respond.
  • Dispatch: trigger method of operation behavior. Is the only method that can execute an action.
  • Actions: Action handling module. Handles all interactions received by the Vue Components. Contains synchronous/asynchronous operations and supports multiple methods of the same name that are triggered in the order of registration. Requests to the background API are made in this module, including triggering other actions and submitting mutations. This module provides the encapsulation of promises to support the chain firing of actions.
  • Commit: State changes commit operation method. Committing for mutation is the only way to perform mutation.
  • Mutations open the door. Is the only recommended method for Vuex to modify state. Other modification methods will report errors in strict mode. This method can only perform synchronous operations, and the method name must be globally unique. Some hooks will be exposed during the operation for state monitoring and so on.
  • State: page state management container object. Centralized storage of scattered data objects in Vue Components, globally unique, for unified state management. The data required for page display is read from this object, leveraging Vue’s fine-grained data response mechanism for efficient status updates.

In a word:

The Vue component received the interaction behavior and invoked the Dispatch method to trigger the relevant action processing. If the page state needed to be changed, the COMMIT method was called to submit the mutation modification state. The new value of state was obtained through getters, and the data or state was responded to the Vue component, and the interface was updated accordingly.

3. Use of Vuex

1. Install

npm install vuex --save

2. Create a folder store and create inde.js

Whatever you want to call it, whatever folder you want to create. For regulation.

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

// Prepare actions to respond to actions in the component
const actions={
}
// prepare mutations-- for data manipulation
const mutations={    
}
// Prepare state-- equivalent to data, used to store data
const state={
    
}
// instantiate create and export store
export default new Vuex.Store({
    namespaced: true.// Resolve module naming conflicts
    actions,
    mutations,
    state,
})

Copy the code

Note:

We import and reference Vuex when we create the index.js file in this step because we want to instantiate the Vuex object. Importing in main will result in an error when importing store in main.js.

3. Add the index. Js from the previous step to main.js and add the store object when instantiating the Vue object:

import store from './store/index' // Import the written store.new Vue({
 el: '#app',
 router,
 store,/ / use the store
 template: ' '.components: { App }
})
Copy the code

Ok, environment set up, start operation.

4. Simple use:

First, a little simple storage data, take out the view. After a series of operations our VM (View Model) and VC (View Component) already have the store data source object. So we can get data from store using this.$store.state. XXX.

Prepare the data in index.js

const state={
    name:'The Romantic code farmer'.age:18,}Copy the code

Get the data in the component

<template>
  <div>{{this.$store.state.name}}, {{this.$store.state.age}}</div>
</template>
Copy the code

5. Mutation, anction

It’s good to know that every VM and VC has a store.

Mutation — The only way to change the state in the store

According to the schematic diagram above, we can know that the state in store can only be changed by mutation submission in VUEX, including the operation in action, which can also be changed by mutation submission. Another point is that VUEX specifies that mutation cannot include asynchronous operations

Let’s modify the name and age properties above.

const mutations = {
    modify_age(state) {// Change the age attribute without arguments. State is the default argument
        state.name = "Zhang";
        state.age = 20;
    },
    modify_age2(state,payload) {// The payload is the object that is passed in.state.name=payload.name; state.age=payload.age; }}Copy the code

In the component, we’ll use this. codestore.com MIT (‘ XXX (method name)’, parameter;

Arguments can be objects or single properties

<template>
  <div>{{this.$store.state.name}}, {{this.$store.state.age}}<button @click="setDefault">Modify without parameters</button>
    <button @click="setparameter">With reference to modify</button>
  </div>
</template>

<script>
export default {
  methods: {
    setDefault() {
      this.$store.commit("modify_age");
    },
    setparameter() {
    this.$store.commit("modify_age2", {name:"Fifty".age:100});// In payload form, passing in can make an object or a single attribute
      Use new code.store.mit ({new code.store.mit ({new code.store.mit ({new code.store.mit))
      // type: "modify_age2",
      // name: "wang Wu ",
      // age: 100,
      // });}); ,}}};</script>
Copy the code

Anction — Synchronous/asynchronous change state

Action is similar to mutation, except that:

  • The Action commits mutation rather than a direct state change.
  • Actions can contain any asynchronous operation.

Background API requests are made in this module. All operations are finally performed by mutation to change the state of state.

As in the previous example, asynchronously modify the state property

On the first code

const actions = {
    asy_modify (context) {/ / no arguments
        setTimeout(() = > {// Asynchronous operation
            context.commit("modify_age")},2000);
      },
      asy_modify2 (context,plyload) {/ / a parameter
        setTimeout(() = > {
            context.commit("modify_age2",plyload);
        }, 2000); }}const mutations = {
    modify_age(state) {// Change the age attribute without arguments. State is the default argument
        state.name = "Zhang";
        state.age = 20;
    },
    modify_age2(state,payload) {// The payload is the object that is passed in.state.name=payload.name; state.age=payload.age; }}const state = {
    name: 'The Romantic code farmer'.age: 18,}Copy the code

Use this.$store.dispatch(‘ XXX ‘) in the component

<template>
  <div>{{this.$store.state.name}}, {{this.$store.state.age}}<button @click="setDefault">Modify without parameters</button>
    <button @click="setparameter">With reference to modify</button>
  </div>
</template>

<script>
export default {
  methods: {
    setDefault() {
      this.$store.dispatch("asy_modify");
    },
    setparameter() {
      this.$store.dispatch("asy_modify2", {name:"Fifty".age:100});// In payload form, passing in can make an object or a single attribute
      // this.$store. Dispatch ({// this.$store
      // type: "asy_modify2",
      // name: "wang Wu ",
      // age: 100,
      // });,}}};</script>
Copy the code

And watch the time, 2 seconds.

Analyze a wave:

  1. The function inside the Action accepts a context object with the same methods and properties as the store instance, so you can submit a mutation by calling context.mit. Or get state and getters via context.state and context.getters.

  2. Action events can also be triggered using both payloads and objects

6. getter

A getter is a derived state of the store state, or a calculated property. Like a calculated property, the return value is cached according to its dependency, and it is recalculated only when the dependent object changes.

A getter property is a common computing property that requires the same processing of data by multiple components.

So that’s pretty clear

The Getter takes state as its first argument and can also use the arrow function.

const getters = {
    get_object: function (state) {/ / no arguments
        if (state.age < 18) {
            return state.name + 'minor'
        }
        return state.name + 'Come of age'
    },
    get_object2: function (state) {/ / a parameter
        return function(value){
            returnstate.name + value; }}}Copy the code

{this.$store.getters. XXX

<template>
  <div>{{this.$store.state.name}}, {{this.$store.state.age}}<br />
    <span>{{this.$store.getters.get_object}}</span>
    <br />
    <span
      >{{this.$store. Getters. Get_object2 (" $store. Getters. ")}}</span ></div>
</template>
Copy the code

7.Modoules

Vuex allows us to split the Store into modules. Each module has its own state, mutation, action, getter, and even nested submodules. Here but more introduced, look at the official documentation (Module | Vuex (vuejs.org))

8. Auxiliary functions

Vuex provides several auxiliary functions, including mapState, mapGetter, mapMutation and mapAction. These are short forms of complex sentences.

Introduction of function

import {mapState,mapGetters,mapMutation,mapAction} from 'vuex'
Copy the code

mapState

If there’s a lot of data in state, we’ll have to repeat a lot of code like this.$store.state.XXX, which we can map to by mapState.

The way to write an array

export default {
  computed: {... mapState(['name'.'age'])// It is automatically added to the calculated properties and can be accessed directly as if it were the calculated properties}};Copy the code

If you want to name an alias, write it as an object

. mapState( {myname: 'name'.myage: "age",}Copy the code

mapGetters

MapGetters are very similar to mapState, but mapGetters. Replace this $store. Getters. XXX

computed: { ... mapGetters(['get_object'.'get_object2']),// Write it as an array. mapGetters({get1:'get_object'.get2:'get_object2'})// Alias can be used as an object
  },
Copy the code

mapMutation

Replace this.$store.com MIT (‘ XXX ‘)

computed: { ... mapMutation(['modify_age'.'modify_age2']),// Write it as an array. mapMutation({modify:'modify_age'.modify2:'modify_age2'}),// Alias can be used as an object
  },
Copy the code

mapAction

Replace this $store. Dispatch (‘ XXX ‘)

computed: { ... mapAction(['asy_modify'.'asy_modify2']),// Write it as an array. mapAction({act_modify:'asy_modify'.act_modify2:'asy_modify2'})// Object form
  },
Copy the code

All of the above auxiliary functions, involving passing parameters, need to be passed when using the computed property.

Write at the end

More specific please see the official website documents, welcome you to guide jiangshan.

See the last “like”, I heard that the comment section can draw oh!