1. What is Vuex?

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

When a project is large, each component has a large number of states. To facilitate management, states in the components need to be extracted and put into Vuex for unified management. Common logins, shopping carts, etc. Data storage

State: The only data source we need to put into State any variables that need to be extracted from any component

Getters: You can derive some new states from Getters

Mutations: The only way to change the state in Vuex’s store is to submit mutation

Actions: The Action commits mutation instead of directly changing the status. The Action can contain any asynchronous operation, but mutation must be a synchronous operation.

Operation steps: When the state of the component changes, it is submitted to Action through the Dispatch function, and then submitted to Mutations through the Actions function. At this time, the component will be rendered in real time if the state changes.

How will VUEX be used in the project

In our project, install vuex

npm install vuex –save

In the SRC directory, create the Store file and create the name of the module in vuex, each separately for easy module management.

Then import it in your main.js file

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

new Vue({
  router,
  store,
  render: h= > h(App)
}).$mount('#app')
Copy the code

In your index.js equivalent to vuex’s home directory, files are introduced in the index.js file

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

export default new Vuex.Store({
        state:{
		
	},
	mutations:{
		
	},
	actions: {},})Copy the code

State defines all states, mutations defines the method for synchronous processing, and Actions defines the method for asynchronous processing

Then give a simple example of logging in to access token values

Synchronization method:

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

export default new Vuex.Store({
        state: {// Define the access token state
	   token:' '
	},
	mutations: {// Synchronous processing
	   set_token(state,action){
               state.token=action
           }
	},
	actions: {},})Copy the code

Call the method in the component to finish storing the token value

1 this.$store.commit("set_token", token);

Asynchronous methods:

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

export default new Vuex.Store({
        state: {// Define the access token state
	   token:' '
	},
	mutations: {// Synchronous processing
	   set_token(state,action){
               state.token=action
           }
	},
	actions: {// Asynchronous invocation
	   setToken(context,action){
               context.commit('set_token',action)
           }
	},
})
Copy the code

Call the method in the component to finish storing the token value

1 this.$store.dispatch("setToken", token);