Detailed explanation of the core concepts and basic usage of Vuex

Detailed explanation of the core concepts and basic usage of Vuex

introduce

Vuex is a mechanism for managing the global state (data) of components, which can easily realize data sharing between components.

start

Install

① Direct download method

Create a vuex.js file and put the content of the URL https://unpkg.com/vuex into the folder.

②CND method

<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script>

③NPM method

npm install vuex --save

④Yarn method

yarn add vuex

How to use NPM installation

1. Create a store/index.js folder in the scr file and write the following content.

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {}
})

2. Import it in main.js and then mount it to the Vue instance

import Vue from 'vue'
import store from './store'
new Vue({
  render: h => h(App),
  store
}).$mount('#app')

Store concept and usage

concept:

It is used to share data between components.

Only mutations can modify data in the store.

use:

Define before use

definition

state: {
  num: 0
}

use

Method 1 (recommended)

<div>{{ numAlias ​​}}</div>

import { mapState } from 'vuex'
export default {
  //Calculation function computed: mapState({
    // Passing the string parameter 'count' is equivalent to `state => state.count`
    numAlias: 'num', // Common key is a name you give yourself, value is the data you receive // ​​Arrow function can make the code more concise count: state => state.count,
    // In order to be able to use `this` to get the local state, you must use the regular function countPlusLocalState (state) {
      return state.count + this.localCount
    }
    //You can define other calculation functions}),
  //Or like this //Calculated function computed: {
    mapState(['count'])
  }
}

Method 2

<div>{{ $store.state.count }}</div>

Mutations concept and usage

concept:

Modify the data in the store. Strictly prohibit modifying the data in other places. Do not perform asynchronous operations in mutations.

Mutations must be executed synchronously and cannot be executed asynchronously.

use:

Define the method before using it

definition

mutations:
	//increment custom method store parameter is store data, parameter parameter is received data, do not increment (state, parameter) {
        // Change state state.num++
    }
}

use

Method 1 (recommended)

import { mapState, mapMutations } from 'vuex'
//Methods: {
	...mapMutations([
	    // mutations custom method name 'increment'
    ]),
    love() {
    	// Directly this calls this.increment('The data that needs to be passed is not needed')
        this.increment('Bin')
    }
}

Method 2

methods: {
    love() {
    	// this.$store.commit('custom name', 'data passed may not be passed')
    	this.$store.commit('increment', 'data')
    }
}

Action concept and usage

concept:

Used to handle asynchronous operations.

If you want to change data through asynchronous operations, you must use actions instead of mutations. However, you still need to indirectly change data by triggering mutations in actions.

Action is similar to mutation, except that:

  • Action submits a mutation instead of directly changing the data (status).
  • Action can contain arbitrary asynchronous operations.

definition

mutations:
	//increment custom method store parameter is store data, parameter parameter is received data, do not increment (state, parameter) {
        // Change state state.num++
    }
},
actions: {
	//add custom method context is a parameter, you can treat it as an instance of vuex add(context) {
    	//You can use context.commit('method to be called in mutations')
    	context.commit('increment')
    }
}

use

Method 1 (recommended)

import { mapState, mapMutations, mapActions } from 'vuex'
export default {
  methods: {
    ...mapActions([
      'add', // Map `this.add()` to `this.$store.dispatch('add')`
      // `mapActions` also supports payloads:
      'add' // maps `this.add(amount)` to `this.$store.dispatch('add', amount)`
    ]),
    ...mapActions({
      add: 'add' // Map `this.add()` to `this.$store.dispatch('increment')`
    }),
    love() {
    	// Directly call this.add('The data that needs to be passed is not needed')
    	this.add(data)
    }
  }
}

Method 2

methods: {
    love() {
    	// this.$store.dispatch('custom name', 'data passed may not be passed')
    	this.$store.dispatch('add', data)
    }
}

Concept and use of getters

concept:

Getter is used to process the data in the store to form new data. Getting can process the existing data in the store to form new data, similar to the calculation abbreviation of Vue.

definition

state: {
  num: 0
},
getters: {
    doneTodos: state => {
    	return state.num = 10
    }
}

use

Method 1 (recommended)

<div>{{ doneTodos }}</div>

import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
  //Calculation function computed: {
  	...mapState(['count']),
  	...mapmapGetters(['doneTodos'])
  }
}

Method 2

<div>{{ $store.getters.doneTodos }}</div>

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Getting Started Tutorial on How to Use Vuex
  • Still using vuex? Learn about pinia
  • Detailed tutorial on using actions in Vuex
  • VueX installation and usage basic tutorial
  • Detailed explanation of the use of Vuex in Vue learning
  • Detailed explanation of the properties and functions of Vuex
  • How to use vuex in Vue project
  • Detailed explanation of Vuex overall case
  • In-depth understanding of the role of Vuex
  • Understanding Vuex in one article
  • Vuex detailed introduction and usage

<<:  A simple way to put HTML footer at the bottom of the page

>>:  MySQL data aggregation and grouping

Recommend

Summary of commonly used escape characters in HTML

The commonly used escape characters in HTML are s...

Understanding MySQL clustered indexes and how clustered indexes grow

In this note, we briefly describe What is the B+T...

Vue implements the countdown component for second kills

This article shares the specific code of Vue to i...

Seven ways to implement array deduplication in JS

Table of contents 1. Using Set()+Array.from() 2. ...

mysql 5.7.18 winx64 free installation configuration method

1. Download 2. Decompression 3. Add the path envi...

MySQL 8.0.12 installation and configuration method graphic tutorial

Record the installation and configuration method ...

Realizing the effect of carousel based on jQuery

This article shares the specific code of jQuery t...

How to configure CDN scheduling using Nginx_geo module

Introducing the Geo module of Nginx The geo direc...

Essential bonus items for optimizing and packaging the front end of Vue projects

Table of contents Preface 1. Routing lazy loading...

MySQL full backup and quick recovery methods

A simple MySQL full backup script that backs up t...

Instructions for recovering data after accidental deletion of MySQL database

In daily operation and maintenance work, backup o...