What is Vuex?

Specialized in Vue to achieve centralized state (data) management of a Vue plug-in, Vue should be used in multiple components of the shared state centralized management (read/write), is also a component communication method, and is suitable for any component communication. You can actually understand “sharing” data.

Second, the principle of Vuex

1. Vuex principle

All vuEX data operations must be carried out through the process of Action -> mutation -> State (reactive data), and then combined with the two-way binding feature of Vue data view to realize page display update.

2. Vuex schematic diagram

Principle/Process analysis:

Vuex consists of three main parts: Actions, Mutations and State

  • Actions: Indirectly updates state(data) in response to Actions in components, including synchronous/asynchronous operations, supports multiple methods of the same name, triggered in the order of registration;

Action does not modify the data directly, but changes it through mutations, which needs to be noted

  • Mutations: used for manipulating data and directly operating to update state(data), which is the only recommended method for Vuex to modify state. Asynchronous operation is not allowed, and the method name can only be globally unique.
  • State: Used to store data. All data displayed on the page is read from the State object. The method name is also globally unique.
  • Vue Components: Vue Components, which are responsible for receiving the interactive behavior of user operations on the page and executing the Dispatch method to trigger the corresponding Actions for response;
  • Dispatch: action trigger method, which is the only method that can execute Actions;
  • Commit: state changes to submit the operation method, and submit mutations, which is the only method that can execute mutations;
  • Devtools: the official debugging tool, very convenient to debug Vuex data changes in the project, mainly used to test Mutations;
  1. Vue Components, in which $store. dispatch (‘ corresponding action callback name ‘) triggers Actions in response to Actions in the component;
  2. Trigger mutations by using COMMIT (‘ corresponding mutations method name ‘) in Actions;
  1. Mutations internally operates the data State, and Vue internally renders the data after operation to the page.

Vuex can be understood with this popular example:

Vue Components is the guest who goes to a restaurant, Actions is the waiter, Mutations is the kitchen, the key to whether the dish tastes good or not is in the kitchen, and State is what the guest orders.

The guest comes in and talks and asks for two egg-fried rice. The server takes the information and submits the menu via the ordering system: two egg-fried rice. When the waiter submits the menu, he calls commit, commit(‘JIA’,2)), and then the order information is transmitted to the kitchen. At this time, the kitchen makes a series of processing of the dish, and finally presents it to the customer.

If the guest is familiar enough with the restaurant, he can order directly from the chef without going through the waiter. That is to say, Actions respond to the action of the component, but it is not necessary. The component can submit mutations directly, without the step of Actions. As long as the waiter must pass the mutations, that is, the restaurant has changed its cuisine, and the previous dishes will not be served, and the guest must pass the waiter to order the menu (Note: The new menu acts as data in the BACKEND API server and can be operated asynchronously.

Three, Vuex usage

  1. Create a folder named store under SRC and create a file named index.js under store. The basic code is as follows

Basic code:

Import Vue from 'Vue' import Vuex from 'Vuex' vue. use(Vuex) // Create and expose store export default new Vuex.Store({// Actions - Used in response to actions in components (equivalent to: servers) actions: {//... Mutations -- for manipulating the data (equivalent to the chef) : {//... }, // state-- store data (equivalent to: customer order menu) state: {//.. }, // getters-- to process data in state (equivalent to calculating attributes) getters: {//.. }})Copy the code

Such as:

Import Vue from 'Vue' import Vuex from 'Vuex' vue. use(Vuex) // Create and expose store export default new Vuex.Store({// Actions - Used to respond to actions in the component (equivalent to: server) Actions: {jiaOdd(context, value) {console.log(context, value); // value: your pass parameter console.log(' jiaOdd from actions was invoked '); Sum (context.state.sum % 2) {context.com MIT ('JIA', value)}},}, {JIA(state, value) {// value: your console. Log ('mutations JIA is called '); Sum += value},}, // state-- store data (equivalent to: customer order menu) state: {sum: Getters: {bigSum(state) {return state.sum * 10},}})Copy the code
  1. Introduce store in main.js

main.js:

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

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
Copy the code
  1. Used in components
<template> <div> <h3> Vuex learning: summation case </h3> <p> Current summation: {{$store.state.sum}}</p> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option Value ="3">3</option> </select> <button @click="increment"> </button> <button @click="incrementOdd"> </div> </template> <script> export default {data(){return{n:1// user select number}}, methods:{increment(){console.log('+'); This. codestore.mit ('JIA',this.n)}, incrementOdd(){console.log(' now sum is odd plus '); // Call the actions method this.$store.dispatch('jiaOdd',this.n)},}} </script>Copy the code
  1. About auxiliary functions

An easier way to use Vuex is with auxiliary functions: mapState, mapGetters, mapActions, mapMutations

<template> <div> <h3>vuex learning: sum case _mapActions and mapMutations</h3> <p> Current sum: {{sum}}</p> <p> Current sum method 10 times: {{$store. Getters. BigSum}} < / p > < p > I'm {{school}}, learning {{subject}} < / p > < select v - model. Number = "n" > < option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button @click="increment(n)">+</button> <button @click="decrement(n)">-</button> <button @click="incrementOdd(n)"> </button> </button> </div> </template> <script>  import { mapState, mapGetters, mapActions, mapMutations } from "vuex"; Export default {data() {return {n: 1, // select a number}; }, computed: { // sum(){ // return this.$store.state.sum // }, // school(){ // return this.$store.state.school // }, $store. State. Subject (){$store. State. / /... MapState ({a:'sum',haha:'school',na:'subject'}) // Array writing (calculate attribute value and state value must be consistent) :... MapState (["sum", "school", "subject"]), // Use mapGetters to generate calculation properties, read data from the getter. mapGetters({ bigSum: "bigSum" }), ... mapGetters(["bigSum"]), }, methods: Use this. dollar () {// // use this. dollar ($store.mit) to call the method in mutations. // }, // decrement() { // this.$store.commit("JIAN", this.n); Open embolization (mutations); open embolization (mutations); open embolization (mutations); MapMutations ({increment: 'JIA', decrement: 'JIAN'}), / / array (written) / /... MapMutations (['JIA','JIAN']), // incrementOdd() {// console. // // invoke actions with this.$store.dispatch("jiaOdd", this.n); // this. / /}, / / incrementWait () {/ / console log (" wait for a moment to add "); // this.$store.dispatch("jiaWait", this.n); }, // generate a method with mapActions that calls dispatch to call actions... MapActions ({incrementOdd:'jiaOdd',incrementWait:'jiaWait'}) mapActions(['jiaOdd','jiaWait']) }, created() { console.log("mapState=", mapState); }}; </script> <style> </style>Copy the code

Iv. Application scenarios of Vuex/When should Vuex be used

  1. When multiple components depend on uniform data or state;
  2. When behavior from different components needs to change the same state;

V. Persistent storage of Vuex

There is a problem with Vuex data: the data is lost when the page or browser is refreshed

Solution: Use Vuex – PersistedState for persistent storage of VUex data

Add: Vuex is not recommended in Vue3, Pinia is officially recommended.

Because Vuex API design, support for TS type derivation is complex, TS will be a pain to use. To solve this problem, the authors of Vuex released Pinia, which they call the next generation of Vuex.


Vi. Vue thinking questions

1. What is the difference between Actions and mutations for Vuex?

  1. Actions are mainly used in response to actions in the component. The mutation function is triggered by commit(), which indirectly updates the state, and is not required to exist.

Mutations are mainly used to directly manipulate data and modify data, which must exist;

  1. Actions can be used for asynchronous operations and can be used to submit data to or accept data from the background.

Mutations is a synchronous operation, which cannot write asynchronous code and can only operate state, which is used to write data information in the global data state cache, and cannot be operated asynchronously.