search
HomeWeb Front-endJS TutorialLet's talk about my understanding of vuex

Let's talk about my understanding of vuex

Jun 26, 2017 pm 01:30 PM
vuexwholecoreconcept

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!

Statement
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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor