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

Web design and production test questions and reference answers

<br />Web Design and Production Test Part I ...

Detailed explanation of 8 ways to pass parameters in Vue routing components

When we develop a single-page application, someti...

Syntax alias problem based on delete in mysql

Table of contents MySQL delete syntax alias probl...

Alibaba Cloud Centos7 installation and configuration of SVN

1. Install SVN server yum install subversion 2. C...

Native js to achieve seamless carousel effect

Native js realizes the carousel effect (seamless ...

How to solve the margin collapse problem in CSS

First, let's look at three situations where m...

jQuery achieves seamless scrolling of tables

This article example shares the specific code of ...

Docker time zone issue and data migration issue

Latest solution: -v /usr/share/zoneinfo/Asia/Shan...

Steps to transfer files and folders between two Linux servers

Today I was dealing with the issue of migrating a...

Example of how to change the line spacing of HTML table

When using HTML tables, we sometimes need to chan...

Detailed explanation of how Tomcat implements asynchronous Servlet

Preface Through my previous Tomcat series of arti...

Display flex arrangement in CSS (layout tool)

Regarding display: flex layout, some people have ...