How to use vuex

Posted by adam1984 on Mon, 08 Nov 2021 17:24:42 +0100

1, Introduction to vuex  

Vuex is an essential part of using vue. Based on parent-child and brother components, it is convenient for us to transfer values. However, if the same set of data is used between unrelated components, it seems powerless. Then vuex can solve our problem. It is equivalent to a public warehouse, which can save the data shared by all components

Using vuex in the project will make us optimize functions, be more comfortable, and improve the fun of code creation. Let me take you to see how to use it in vue project

2, Suitable for beginners to save data and obtain data

1. Create a new index.js file in the store folder (the name of the folder can be taken arbitrarily. If there is no such folder, you can create a new one. Of course, you can also create a new index.js file directly without creating a folder, which will not affect the use)

Write the following code in the new js file

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

export default new Vuex.Store({
   state:{
     pathName:"",
     currDbSource: {},
     currJobDate: {},
     DbSource:[]
   },
   mutations:{
     //Saves the path of the current menu bar
     savePath(state,parhName){
       state.pathName = pathName;
     },
     //Save the currently clicked data source
     saveCurrDbsource(state,currDbSource){
       state.currDbSource = currDbSource;
     },
     //Save the metadata of the current Click
    savecurrJobDate(state,currJobDate){
      state.currJobDate = currJobDate
    },
    //Save all data sources
    saveDbSource(state, DbSource){
       state.DbSource =  DbSource
    }
   }
})

Here we explain the functions of the above codes. State is some custom variables that need to save data. mutation is used to trigger events, which is equivalent to a method. The user needs to trigger this method to save data. For parameters, the second parameter is the value passed in by the user, and then assigned to the variable in state in the method

2.main. Import: (just pay attention to the path)

//Introducing vuex -store
import store from './store/index.js'

new Vue({
 el: '#app',
router,
store,
render:h => h(App)
});

3. Save data: (scenario example: when we click the button, we need to save the current data to vue, then jump to another route, and then use these data)

methods:{
  click(){
  //Click the button to perform some operations, and then save the data
  this.$store.commit('saveCurrDbSource',this.db)
   }  
}

The first parameter here is the method to be triggered, that is, the method in the above changes, and the second parameter is the data to be passed

4. Obtain variables: (when the initial data cannot be obtained, the calculation attribute can be used to obtain)

this.$store.state.Variable name

//for example
this.$store.state.currDbSource

In this way, other components can share the saved data and modify it accordingly

Two. Modularization

Of course, in the above method, we write everything in one file. When there is too much data, it looks too bloated and is not conducive to maintenance. Moreover, changes can not solve the asynchronous problem. Here is another method and actions

actions: everyone who has read the introduction on the official website knows that this is an intermediary that indirectly triggers the changes method, and it can perform asynchronous operations to avoid users directly operating atate

1.state.js: save all data and export it as an object

export default {
 pathName :'' , //route
 currDbSource :{},//Current data source
 currJobData :{},//Current data source
 DbSource :[],//Therefore, the data source is used for the drop-down list in the metadata interface
 selectJobMeta:{},//Currently selected metadata (single data clicked after search)
 specialSubject:[].//Multiple data
 duplicateJobMeta:{},//Replicated data
};

2. Changes. JS: save all methods to change the state data

//Saves the path of the current menu bar
export const savePath = (state ,pathName)=> {
  state.pathName = pathName
};

//Save the currently clicked data source
export const saveCurrDbsource = (state ,CurrDbsource)=>{
  state.currDbSource = currDbSource;
}

//Save the metadata of the current Click
export const savecurrJobDate = (state ,currJobDate)=>{
  state.currJobDate = null ;
  state.currJobDate = currJobDate
};

//Save all data sources
export const saveDbSource = (state ,DbSource)=>{
  state.DbSource = DbSource
};

There are two methods:

//Method 1:
export const saveDbSource = (context,payload) => {
 context.commit('saveDbSource',payload);
};

//Method 2:
export const saveDbsource = ( { commit },payload) => {
  commit('saveDbSource' ,payload);
}

The first is to trigger events through the context. The other is to directly use commit. In order to save data, the second parameter payload needs to be added. Otherwise, the data saved to vuex is null

4.index.js: introduce corresponding modules and expose the store for global use after vue registration

5. Introduce index.js into main.js

6. Save data

There are two methods to save data. The first is the direct operation method, which is sent to actions through dispach to let actions trigger

The second way is to add a mapping relationship in methods, which means that we can write multiple methods in the array (here, each method name of the array is the method name defined in the actions.js file), and then directly this where we need to use it. Of course, it can also be directly bound to an event in html

It is worth noting that avoid conflicts with the names of other methods defined in methods

7. Access to data

By calculating attributes, when the data changes, we can ensure that we get the data after the response, which is also in the form of array, which also means that we can get multiple groups of data. Here, the array is also a variable defined in state.js

When using, you can get it directly through the name of this. Variable, such as this.DbSource in this example. We can assign it to our custom variable or use it directly

The value should avoid conflicts with the names of other variables defined in data

So far, we have completed the storage and data acquisition of vuex. I hope it will be helpful to you.

Of course, we need to filter a group of data in a vuex, and other components share the filtered data. In this case, you may use getters. I won't repeat it here. Interested partners can learn about it by themselves.

The running process of vuex and the pictures on the official website are attached: the component sends tasks to actions, which triggers the methods in changes, and then changes the data in the state. After the data changes, the response is pushed to the component, and the component re renders


--------

Topics: Javascript Front-end Vue.js