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 learning HTML tags and basic elements

1. Elements and tags in HTML <br />An eleme...

Implementation of dynamic rem for mobile layout

Dynamic rem 1. First, let’s introduce the current...

Implementation of mysql split function separated by commas

1: Define a stored procedure to separate strings ...

JavaScript to implement click to switch verification code and verification

This article shares the specific code of JavaScri...

JavaScript implements draggable progress bar

This article shares the specific code of JavaScri...

Notes on using the blockquote tag

<br />Semanticization cannot be explained in...

Configuring MySQL and Squel Pro on Mac

In response to the popularity of nodejs, we have ...

How to allow all hosts to access mysql

1. Change the Host field value of a record in the...

Simple example of adding and removing HTML nodes

<br />Simple example of adding and removing ...

Use viewport in meta tag to define screen css

<meta name="viewport" content="w...

HTML table tag tutorial (19): row tag

The attributes of the <TR> tag are used to ...

JavaScript implements the nine-grid mobile puzzle game

This article shares the specific code for JavaScr...

Summary of the characteristics of SQL mode in MySQL

Preface The SQL mode affects the SQL syntax that ...

How to adjust the log level of nginx in Docker

Table of contents Intro Nginx Dockerfile New conf...