Home Web Front-end JS Tutorial Let's talk about my understanding of vuex

Let's talk about my understanding of vuex

Jun 26, 2017 pm 01:30 PM
vuex whole core concept

vuex exists to solve the problem of communication between vue components and components. vuex is a little complicated to understand, but once you understand it, it is easy to use:

Installation:

npm install --save vuex
Copy after login

Introduction

import Vuex
Copy after login

Introduction to several parameters of vuex

State Store initialization data

Getters Secondary processing of data in State (Filtering data is similar to filter) For example, State returns an object. If we want to get the value of a key in the object, use this method

Mutations. All methods for calculating data are written in it (similar to computed ) Use this.$store.commit('mutationName') when triggering in the page to trigger the Mutations method to change the value of the state

Actions The direct triggering method for processing methods that have been written in Mutations is this.$store. dispatch(actionName)

Let’s not rush to learn more first. Let’s print out Vuex

console.log(Vuex) //Vuex为一个对象里面包含Vuex ={
    Store:function Store(){},    
    mapActions:function(){},    // 对应Actions的结果集mapGetters:function(){},    //对应Getters的结果集mapMutations:function(){},  //对应Mutations的结果集mapState:function(){},      //对应State的结果集install:function install(){}, //暂时不做讲解 installed:true //暂时不做讲解}//如果我们只需要里面的State时我们可以这样写import { mapState } from 'vuex';
import { mapGetters, mapMutations } from 'vuex'; //如果需要引用多个时用这种方式处理
Copy after login

If you read the above content repeatedly, it will suddenly become clear. Next, let’s proceed. Take the following examples and describe them in official language

State

State is responsible for storing the state data of the entire application. Generally, you need to inject the store object into the node when using it. You can use this.$ later. store.state directly obtains the state

//store为实例化生成的import store from './store' new Vue({
  el: '#app',
  store,
  render: h => h(App)
})
Copy after login

This store can be understood as a container, including the state in the application, etc. The process of instantiating and generating a store is:

//./store文件const store = new Vuex.Store({
  state: {   //放置state的值
    count: 0,
    strLength:"abcd234"
  },
  getters: {   //放置getters方法
      strLength: state => state.aString.length
  },
  mutations: {   //放置mutations方法
       mutationName(state) {          //在这里改变state中的数据  state.count = 100;
       }
  },  // 异步的数据操作  actions: {      //放置actions方法
       actionName({ commit }) {          //dosomething commit('mutationName')
      },
      getSong ({commit}, id) {
          api.getMusicUrlResource(id).then(res => {
            let url = res.data.data[0].url;
        
          })
          .catch((error) => {  // 错误处理              console.log(error);
          });
      }
  }
});
export default store;
Copy after login

During subsequent use in components, if you want to obtain the corresponding state, you can directly use this.$store.state to obtain it. Of course, you can also use the mapState auxiliary function provided by vuex to map state to calculated properties, such as

import {mapState} from 'vuex'export default {  //组件中
  computed: mapState({
    count: state => state.count
  })
}
Copy after login

Getters

Some states require secondary processing, just Getters can be used. Access the derived state through this.$store.getters.valueName. Or directly use the auxiliary function mapGetters to map it to local calculated properties.

How to use it in components

import {mapGetters} from 'vuex'export default {  
computed: mapGetters(['strLength'])
}
Copy after login

Mutations

Mutations means "change" in Chinese. It can be used to change the state. Its essence is to A function that processes data and receives the unique parameter value state. store.commit(mutationName) is a method used to trigger a mutation. What needs to be remembered is that the defined mutation must be a synchronous function, otherwise there may be problems with the data in the devtool, making state changes difficult to track.

Trigger in the component:

export default {
  methods: {
    handleClick() {      this.$store.commit('mutationName')
    }
  }
}
Copy after login

Or use the auxiliary function mapMutations to directly map the trigger function to methods, so that it can be used directly in element event binding . For example:

import {mapMutations} from 'vuex'export default {
  methods: mapMutations(['mutationName'
  ])
}
Copy after login

Actions

Actions can also be used to change the state, but it is implemented by triggering mutations. The important thing is that it can include asynchronous operations. Its auxiliary function is mapActions, which is similar to mapMutations and is also bound to the component's methods. If you choose to trigger it directly, use this.$store.dispatch(actionName) method.

Used in components

import {mapActions} from 'vuex'//我是一个组件export default {
  methods: mapActions(['actionName',
  ])
}
Copy after login

Plugins

The plug-in is a hook function, which can be introduced when initializing the store. The more commonly used one is the built-in logger plug-in, which is used for debugging.

//写在./store文件中import createLogger from 'vuex/dist/logger'const store = Vuex.Store({
  ...
  plugins: [createLogger()]
})
Copy after login

The above is the detailed content of Let's talk about my understanding of vuex. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to enable or disable Core Isolation Memory Integrity in Windows 11, 10 How to enable or disable Core Isolation Memory Integrity in Windows 11, 10 Apr 27, 2023 pm 10:43 PM

Today, most Windows users use virtual machines. When core isolation is disabled on their systems, security risks and attacks are to be expected. Even if core isolation is set, memory integrity is disabled if the user upgrades the system. If core isolation is enabled, the system will be protected from attacks. For people who frequently use virtual computers, it is highly recommended that they enable it. If you are looking for instructions on how to enable or disable Core Isolated Memory Integrity on any Windows 11 system, this page can help. How to Enable or Disable Core Isolation Memory Integrity in Windows 11 using the Windows Security app Step 1: Press the Windows key and type Windows Security

What does the metaverse concept mean? What is the metaverse concept? What does the metaverse concept mean? What is the metaverse concept? Feb 22, 2024 pm 03:55 PM

The Metaverse is an illusory world that uses technology to map and interact with the real world. Analysis 1 Metaverse [Metaverse] is an illusory world that makes full use of technological methods to link and create, and maps and interacts with the real world. It is a data living space with the latest social development system. The 2-dimensional universe is essentially a virtual technology and digital process of the real world, which requires a lot of transformation of content production, economic system, customer experience and physical world content. 3 However, the development trend of the metaverse is gradual. It is finally formed by the continuous combination and evolution of many tools and platforms with the support of shared infrastructure, standards and protocols. Supplement: What is the metaverse composed of? 1 The metaverse is composed of Meta and Verse, Meta is transcendence, and V

Learn more about Gunicorn's fundamentals and features Learn more about Gunicorn's fundamentals and features Jan 03, 2024 am 08:41 AM

Basic concepts and functions of Gunicorn Gunicorn is a tool for running WSGI servers in Python web applications. WSGI (Web Server Gateway Interface) is a specification defined by the Python language and is used to define the communication interface between web servers and web applications. Gunicorn enables Python web applications to be deployed and run in production environments by implementing the WSGI specification. The function of Gunicorn is to

Write a Java program to calculate the area and perimeter of a rectangle using the concept of classes Write a Java program to calculate the area and perimeter of a rectangle using the concept of classes Sep 03, 2023 am 11:37 AM

The Java language is one of the most commonly used object-oriented programming languages ​​in the world today. The concept of classes is one of the most important features of object-oriented languages. A class is like a blueprint for an object. For example, when we want to build a house, we first create a blueprint of the house, in other words, we create a plan that shows how we are going to build the house. According to this plan we can build many houses. Likewise, using classes, we can create many objects. Classes are blueprints for creating many objects, where objects are real-world entities like cars, bikes, pens, etc. A class has the characteristics of all objects, and the objects have the values ​​of these characteristics. In this article, we will write a Java program to find the perimeter and faces of a rectangle using the concept of classes

Introduction and core concepts of Oracle RAC Introduction and core concepts of Oracle RAC Mar 07, 2024 am 11:39 AM

Introduction and core concepts of OracleRAC (RealApplicationClusters) As the amount of enterprise data continues to grow and the demand for high availability and high performance becomes increasingly prominent, database cluster technology becomes more and more important. OracleRAC (RealApplicationClusters) is designed to solve this problem. OracleRAC is a high-availability, high-performance cluster database solution launched by Oracle.

Master the key concepts of Spring MVC: Understand these important features Master the key concepts of Spring MVC: Understand these important features Dec 29, 2023 am 09:14 AM

Understand the key features of SpringMVC: To master these important concepts, specific code examples are required. SpringMVC is a Java-based web application development framework that helps developers build flexible and scalable structures through the Model-View-Controller (MVC) architectural pattern. web application. Understanding and mastering the key features of SpringMVC will enable us to develop and manage our web applications more efficiently. This article will introduce some important concepts of SpringMVC

How to solve the problem 'Error: [vuex] do not mutate vuex store state outside mutation handlers.' when using vuex in a Vue application? How to solve the problem 'Error: [vuex] do not mutate vuex store state outside mutation handlers.' when using vuex in a Vue application? Jun 24, 2023 pm 07:04 PM

In Vue applications, using vuex is a common state management method. However, when using vuex, we may sometimes encounter such an error message: "Error:[vuex]donotmutatevuexstorestateoutsidemutationhandlers." What does this error message mean? Why does this error message appear? How to fix this error? This article will cover this issue in detail. The error message contains

Best practices for using Vuex to manage global state in Vue2.x Best practices for using Vuex to manage global state in Vue2.x Jun 09, 2023 pm 04:07 PM

Vue2.x is one of the most popular front-end frameworks currently, which provides Vuex as a solution for managing global state. Using Vuex can make state management clearer and easier to maintain. The best practices of Vuex will be introduced below to help developers better use Vuex and improve code quality. 1. Use modular organization state. Vuex uses a single state tree to manage all the states of the application, extracting the state from the components, making state management clearer and easier to understand. In applications with a lot of state, modules must be used

See all articles