SoFunction
Updated on 2025-04-05

Detailed explanation of the understanding and use of Vuex newbies

1 conceptual understanding of vuex

When it comes to vuex, you must mention vue first.

I personally started to learn to use vue because I always encountered the consistency between page logic data and views. Before using vue, when we used jQuery plug-in, a troublesome thing was to write code to change the view after each data change, and to consider listening to various events when various inputs on html are changed to change the page logic data. Of course, at the earliest, we used the value inside html to record various data, but this method seems a bit simple and crude today, and it is difficult to use complex page logic. This is exactly the original intention of me to start using vue - data bidirectional binding.

But for vue, there is another very powerful function, which is the component function. There are two understandings of this function: one is to make some simple and light wheels, which are difficult to apply to other projects but are very suitable for multiple pages within the project; the other is to route the page, which means to understand each page as a component, rather than a separate html page;

When I started using vue again, I would new a new vue on each page to implement two-way binding of data inside the page. This usage is understandable and can be compatible with old projects, but there is only one shortcoming (or the general shortcomings of old projects), that is, the management of logical data is based on html pages, and there is no good way to correlate the data between pages (html pages are connected through iframes, but the data communication between each other does not have a good API, and compatibility issues are prone to occur).

vuex is prepared for this. Of course, there is a prerequisite, which is that the page association method must be associated through the vue component. After using this method, some ideas for programming using the foreground vue will undergo some changes. Here are some things we can do through data exchange:

Most of the basic data that is frequently called can be used on all pages, which is suitable for technical occasions;

For components, there are two common attributes, one is data and the other is prop. In my understanding, data is responsible for the internal logic of the component, and prop is responsible for the data association with internal and external data, such as the most common value. However, for the framework composed of routing pages (such as iView), if the routing page is switched, the original routing page data will be cleared. This situation can be avoided by using it to store data at this time. This is suitable for vue component page occasions;

2 Use of vuex

For a front-end project, there must be many vue components, but vuex can only have one ('/src/store/'). Of course, vuex can be spread through import, so that different modules can store different business data. The following is the main content of vuex:

import Vue from 'vue'
import Vuex from 'vuex'

import user from './module/user'
import app from './module/app'
import basedata from './module/basedata'

(Vuex)

export default new ({
 state: {
  //
 },
 mutations: {
  //
 },
 actions: {
  //
 },
 modules: {
  user,
  app,
  basedata
 }
})

The following is one of the branches and leaves: /module/, the module used to store basic data:

import { getCusData, getSupSelect } from '../../api/public'

/**
  * For common basic data reading, pay attention to the following restrictions:
  * 1. Must be read only!!!
  * 2. It must be only in the basic module data!!!
  * 3. At present, it is only to judge whether it is used as a cache by the existence of data, and it may be judged through more reasonable and complex logic in the future.
  * @author YangYishe
  */
export default {
 state: {
  // Customer Collection  arrCustomer: [],
  // Supplier collection  arrSupplier: [],
  
  nowTimes: 0
 },
 mutations: {
  setNowTimes (state, times) {
   // Test the method of vuex state   ('set now times')
    = new Date().getTime() + times
  },
  // Reset customer data  setCustomerData (state, arrCustomer) {
    = arrCustomer
  },
  // Reset vendor data  setSupplierData (state, arrSupplier) {
    = arrSupplier
  },
  
 },
 getters: {

 },
 actions: {
  // Test the method of changing  handleChangeTimes ({ state, commit }, { times }) {
   commit('setNowTimes', times)
  },
  // Read customer data (supports two usages of mapState and return)  loadCustomer ({ state, commit }) {
   // Read customer data (Promise to support asynchronous operations)   if ( === 0) {
    return new Promise((resolve, reject) => {
     getCusData().then(res => {
      commit('setCustomerData', )
      resolve()
     }).catch(err => reject(err))
    })
   } else {
    return 
   }
  },
  // Read supplier data (supports two usages of mapState and return)  loadSupplier ({ state, commit }) {
   if ( === 0) {
    return new Promise((resolve, reject) => {
     getSupSelect().then(res => {
      commit('setSupplierData', )
      resolve()
     }).catch(err => reject(err))
    })
   } else {
    return 
   }
  },
  
 }
}

From this module/, it is easy to see the general logic of this module.

  • The global collection of customer and vendors stored in state;
  • Mutations are generally used to synchronize and change the data in the state, similar to setters;
  • getters are used to calculate various attribute values ​​based on state;
  • actions are to receive data asynchronously (it does not necessarily have to be an asynchronous method, such as the first method, but the external call interfaces are called from here), and then call the internal mutations method to change the value of state;

For external calling methods, please refer to the following (only the necessary codes are listed here):

<template>
  ...
  <!-- Here isiviewframe,soSelectandOptionAll first letters are capitalized -->
  <Select v-model="" clearable filterable>
   <Option v-for="mCustomer in arrCustomer" :key="" :value="">{{}}</Option>
  </Select>
  ...
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default{
  name:'test-temp',
  data(){
    return {
      //
      mCondition:{}
    }
  },
  computed:{
    //Because it is used here, I am not sure whether it is possible to use string arrays.    ...mapState({
      arrCustomer:state=>
    })
    
  },
  created(){
    //The mapActions method is called here. If the original method has parameters, it will start from the second parameter by default, and there is no need to consider {state}    ();
  },
  methods:{
    //The method of string array is adopted here    ...mapActions([
     'loadCustomer',
    ]),
  }
  
}

</script>

The above is how vuex is used. I personally think that the explanation in the comparison has been placed in the comments in the code.

3 Other points of attention

This article is more inclined to let novices understand and get started, so the code is more inclined.

In actual use, the consideration of cache replacement may be more complicated.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.