1. Vuex overview

1.1 How components share data

Parent to child: V-bind attribute binding

Child to parent: V-ON event binding

Sharing data between sibling components: EventBus

  • $on The component that receives the data
  • $emit the component that sends the data

When data sharing is implemented on a large scale, these three schemes are a bit inadequate.

1.2 What is Vuex?

Vuex is a mechanism to implement global state (data) management of components and facilitate data sharing among components.

Vuex is recommended for large scale and frequent data sharing in projects.

1.3 Benefits of unified state management using Vuex

  1. Centralized management of shared data in Vuex for easy development and maintenance.
  2. It can efficiently realize data sharing between components and improve development efficiency.
  3. The data stored in Vuex is responsive and keeps the data in sync with the page in real time

1.4 What kind of data is suitable to store in Vuex

In general, only data shared between components is necessarily stored in Vuex; For private data in the component, it is still stored in the component’s own data.

2. Basic use of Vuex

  1. Install vuEX dependency packages
npm install vuex --save
Copy the code
  1. Import vuex package
import Vuex from 'vuex'
Vue.use(Vuex)
Copy the code
  1. Creating a Store object
  1. Mount the Store object to the Vue instance
import Vue from "vue" import Vuex from "vuex" Vue.use(Vuex) const store = new Vuex.Store({ state: { count: $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$Copy the code

3. The core concept of Vuex

3.1 Overview of core Concepts

The key concepts in Vuex are as follows:

  • State
  • Mutation
  • Action
  • Getter

3.2 the State

State provides the only common data source, and all shared data is stored in the Store State.

const store = new Vuex.Store({
	state:{count:0}
})
Copy the code

The first way a component accesses State data

this.$store.state.count
Copy the code

A second way for a component to access State data

Import {mapState} from 'vuex' import {mapState} from 'vuex'Copy the code
// 2. Map global data to the computed property of the current component, computed:{... mapState(['count']) }Copy the code

# # 3.3 Mutation

Vuex does not allow components to modify Store data between components

Mutation is used to change data in the Store

  1. Store data can only be changed by mutation, but data in Store cannot be manipulated directly.
  2. This is a slightly more cumbersome way to operate, but you can monitor all data changes centrally.
/ / define Mutation
const store = new Vuex.Store({
  state: { count: 0 },
  mutations: {
    add(state) {
      state.count++
    },
  },
})
Copy the code
/ / triggers the Mutation
methods: {add(){
    // The first way to trigger mutation
    this.$store.commit('add')}}Copy the code

Arguments can be passed when mutation is triggered:

/ / define Mutation
const store = new Vuex.Store({
  state: { count: 0 },
  mutations: {
    add(state,step) {
      state.count+=step
    },
  },
})
Copy the code

The first way to trigger mutation

/ / triggers the Mutation
methods: {add(){
    // The first way to trigger mutation
    this.$store.commit('add'.3)}}Copy the code

The second way to trigger mutation

Import {mapMutations} from 'vuex'Copy the code

Mutations function is used to map the necessary mutations function to the methods of the current component through the just imported mapMutations function.

<template> <div> <p> The latest value of count is: {{count}}</p> <button @click="handle2">+1</button> </div> </template> <script> import {mapState,mapMutations} from 'vuex' export default { data(){ return{} }, methods:{ ... mapMutations(['sub','subN']), handle2(){ this.subN(3) } }, computed:{ ... mapState(['count']) } } </script>Copy the code

The second method can be used by calling the mapped method directly with this.

3.4 the Action

Do not perform asynchronous operations in mutation functions

// The following is an error
mutation: {add(state){
    setTimeout(() = >{
      state.count++
    },1000)}}Copy the code

Action Is used to process asynchronous tasks.

If the data is changed by an asynchronous operation, it must be changed through an Action rather than Mutation, but the data must be changed indirectly by triggering Mutation in the Action.

/ / define the Action
const store = new Vuex.Store({
  state: { count: 0 },
  mutations: {
    add(state) {
      state.count++
    },
  },
  actions: {
    addAsync(context) {
      // In actions, you cannot change the state directly, you must change the state by commit.
      setTimeout(() = > {
        context.commit("add")},1000)}}})Copy the code

The first way to trigger actions

/ / triggers the action
methods: {handle(){
    // The dispatch function is specifically used to trigger the action
    this.$store.dispach('addAsync')}}Copy the code

An asynchronous operation cannot modify a value in state directly, but must be modified by mutation.

The action asynchronous task is triggered with parameters

  actions: {
    addAsync(context) {
      setTimeout(() = > {
        context.commit("add")},1000)},addNAsync(context, step) {
      setTimeout(() = > {
        context.commit("addN", step)
      }, 1000)}},Copy the code
  methods:{
    add(){
      // commit calls a mutation function
      //this.$store.commit('add')
      this.$store.dispatch('addAsync')},addN(){
      this.$store.dispatch('addNAsync'.4)}}Copy the code

The second way to trigger actions is:

// 1. Import mapActions functions from vuex as needed
import {mapActions} from 'vuex'
Copy the code
// 2. Map the required actions to the current component's methods using the mapActions function imported just now:
methods: {... mapActions(['addAsync'.'addNAsync'])
  // The addNAsync function can also be used directly in the component. The following code can be omitted
  handle3(){
    this.addNAsync(3)}}Copy the code

Code implementation:

3.5 Getter (Wrapper only)

Getters are used to process data in a Store to form new data.

  1. Getters can process existing data in the Store to form new data, similar to the calculation properties of Vue.
  2. When the data in the Store changes, the data in the Getter changes as well.
/ / define Getter
const store = new Vuex.Store({
	state: {count:0
  },
  getters: {showNum:state= >{
			return 'The current latest quantity is ['+ state.count +'】'}}})Copy the code

The first way to use getters

this.$store.getters.showNum
Copy the code

The second way to use getters

import {mapGetters} from 'vuex' computed:{ .. mapGetters(['showNum']) }Copy the code

Code implementation:

The last

If this article helped you, please like it and add it to GitHub blog at github.com/skyblue309. This article summarizes the most core knowledge points of VEX3.0 in my opinion. There are many details in Vex3.0, such as modules and project structure. If readers are interested, they can see the vex3.0 document.

Vexv3.0 documentation: vuex.vuejs.org/zh/