In-depth understanding of the role of Vuex

In-depth understanding of the role of Vuex

Overview

Those who have used vue.js must know the pain of passing values ​​between vue components. Based on parent-child and brother components, it may be very convenient for us to pass values, but if unrelated components want to use the same set of data, it seems very helpless. Vuex solves this problem very well. Therefore, Vuex must be mastered, and it is also a must-ask question when going out for an interview. Next, we will briefly introduce how vuex manages the status of components.

How to share data between components

Passing values ​​from parent to child: v-bind attribute binding, props receiving; $parent / $children; $refs; $attrs / $listeners;

Child passes value to parent: v-on event binding, combined with $emit trigger; $parent / $children;

Sharing data between sibling components: EventBus; Vuex

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

Introduction to Vuex principles

Vuex implements a one-way data flow and has a global state to store data. When a component wants to change the data in the state, it must be done through mutations. Mutations also provide a subscriber mode for external plug-ins to call to obtain state data updates. When all asynchronous operations (often used to call backend interfaces to asynchronously obtain data) or batch synchronous operations need to go through actions, actions cannot directly modify the state. It is still necessary to trigger the methods in mutations, and then mutations to modify the state data. When the data changes, it is pushed to the component accordingly, and the component is re-rendered on the view.

Vuex is the state manager of Vue, and the stored data is responsive. But it will not be saved. After refreshing, it will return to the initial state. The specific method is to copy the data and save it to localStorage when the data in vuex changes. After refreshing, if there is saved data in localStorage, take it out and replace the state in the store.

Vuex is a mechanism for managing component global state (data)

It is easy to share data between components

The benefits of using Vuex to uniformly manage state:

  • Ability to centrally manage shared data in Vuex, making development and maintenance easier
  • Able to efficiently realize data sharing between components and improve development efficiency
  • The data stored in Vuex is responsive and can keep the data and the page synchronized in real time.

What kind of data is suitable for storing in Vuex

Generally speaking, only data shared between components needs to be stored in Vuex; private data of components can still be stored in the component's own data.

  • Multiple views rely on the same state: for example, data is shared between multiple components, and user information can be obtained on different pages
  • Behaviors from different views need to change the same state: for example, user membership information can be changed on different pages

Basic use of Vuex

1. Install Vuex dependency package

npm install vuex --save

Be sure to add –save because this package will also be used in a production environment.

2. Import the Vuex package

import Vue from 'vue'
import Vuex from 'vuex'
// Mount Vuex
Vue.use(Vuex)

3. Create a store object

const store = new Vuex.Store({
  // The state stores the globally shared data state: {
    count: 0
  }
})
export default store;

4. Mount the store object into the vue instance

new Vue({
    el: '#app',
    render: h => h(app),
    router,
    //Mount the created shared data object into the Vue instance //All components can get global data from the store
})

The main core concepts in Vuex

1. State Data Warehouse

State provides a unique public data source, and all shared data is stored in the State of the Store.

The first way for a component to access data in State: this.$store.state.global data name

The second way for components to access data in State:

// 1. Import the mapState function on demand from vuex import { mapState } from 'vuex'

// 2. Through the mapState function just imported, map the global data required by the current component to the computed property of the current component computed: {
    ...mapSate(['count'])
}

2. Mutation

Mutation is used to change the data in the Store.

You can only change the Store data through mutation, you cannot directly operate the data in the Store, you modify it by committing a mutation, its essence is actually a function

Although this method is a little more complicated to operate, it can centrally monitor the changes of all data.

Mutation operations must be synchronous

Every time we submit a mutation, there will be a record. Vuex does this to more conveniently record the history and track of each data change, which is convenient for monitoring and rollback operations.

The first way to trigger mutations:

// Define mutation in store.js
const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations:
        add(state) {
            state.count++ //Change state}
    }
})
// Trigger mutation in component
methods: {
    handle() {
        // The first method to trigger mutations this.$store.commit('add')
    }
}

Pass parameters when triggering mutations:

//store.js
mutations:
    addN(state, step) { //The first parameter is state, and the following parameters are additional parameters passed in by store.commit, i.e. the payload of the mutation
        state.count += step
    }
}

// In the component this.$store.commit('addN', 3) // Call the commit function and carry parameters when triggering mutations

The second way to trigger mutations:

// 1. Import the mapMutations function on demand from vuex import { mapMutations } from 'vuex'

// 2. Use the newly imported mapMutations function to map the specified mutations function to the methods function of the current component methods: {
    ...mapMutations(['add', 'addN'])
}

Note: Do not perform asynchronous operations in mutation functions, such as adding delays

3. Action

Action is used to handle asynchronous tasks.

If you want to change data through asynchronous operations, you must use an Action instead of a Mutation. However, you still need to indirectly change the data in an Action by triggering a Mutation.

The first way to trigger actions:

//Define Action in store.js
const store = new Vuex.store({
    //...Omit other code actions: {
        addAsync(context, payload) {
            setTimeout(() => {
                context.commit('add')
            }, 1000)
        }
    }
})
// Trigger Action in component
methods: {
    handle() {
        this.$store.dispatch('addAsync', 3)
    }
}

Note: Do not perform asynchronous operations in mutation functions, such as adding delays

Only functions defined in mutations have the right to modify data in the state; data in the state cannot be modified directly in actions, and a mutation must be triggered through context.commit.

context: context object, equivalent to this in the arrow function, has the same properties and methods as the store instance

Payload: the mounted parameters

The second way to trigger actions:

// 1. Import the mapActions function on demand from vuex import { mapActions } from 'vuex'

// 2. Use the newly imported mapActions function to map the specified actions function to the methods function of the current component methods: {
    ...mapActions(['addAsync', 'addN'])
}

4. Getter

Getter is used to process the data in the Store to form new data. Getter will not modify the original data in the Store, it only acts as a wrapper.

Getter can process the existing data in the Store to form new data, similar to Vue's computed properties.

Like computed properties, the return value of a getter is cached based on its dependencies and is only recomputed if the values ​​of its dependencies change. That is, if the data in the Store changes, the data in the Getter will also change.

// Define Getter 
const store = new Vuex.store({
    state: {
        count: 0
    },
    getters: { // Real-time monitoring of state value changes showNum: state => {
            return 'The current latest number is [' + state.count + ']'
        }
    }
})

The first way to use getters: this.$store.getters.name

The second way using getters:

import { mapGetters } from 'vuex'

computed: {
    ...mapGetters(['showNum'])
}

The above is the detailed content for in-depth understanding of the role of Vuex. For more information about Vuex, please pay attention to other related articles 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
  • Detailed explanation of the core concepts and basic usage of Vuex
  • How to use vuex in Vue project
  • Detailed explanation of Vuex overall case
  • Understanding Vuex in one article
  • Vuex detailed introduction and usage

<<:  Nginx's practical method for solving cross-domain problems

>>:  How to process blob data in MySQL

Recommend

A brief introduction to React

Table of contents 1. CDN introduction 1.1 react (...

MySQL restores data through binlog

Table of contents mysql log files binlog Binlog l...

How to configure eureka in docker

eureka: 1. Build a JDK image Start the eureka con...

Detailed explanation of the integer data type tinyint in MySQL

Table of contents 1.1Tinyint Type Description 1.2...

Some methods to optimize query speed when MySQL processes massive data

In the actual projects I participated in, I found...

Solution to Vue's inability to watch array changes

Table of contents 1. Vue listener array 2. Situat...

mysql 8.0.12 winx64 download and installation tutorial

MySQL 8.0.12 download and installation tutorial f...

Creating a Secondary Menu Using JavaScript

This article example shares the specific code of ...

Tutorial on installing GreasyFork js script on mobile phone

Table of contents Preface 1. Iceraven Browser (Fi...

How to implement remote connection for Redis under Linux

After installing Redis on Linux, use Java to conn...

Vue implements the full selection function

This article example shares the specific code of ...

Use of Linux gzip command

1. Command Introduction The gzip (GNU zip) comman...

CSS mimics remote control buttons

Note: This demo is tested in the mini program env...