Let's talk about my understanding of vuex
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
Introduction
import Vuex
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'; //如果需要引用多个时用这种方式处理
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) })
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;
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 }) }
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']) }
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') } } }
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' ]) }
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', ]) }
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()] })
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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 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.

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?](https://img.php.cn/upload/article/000/000/164/168760467048976.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
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

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
