Table of Contents
Installing and using vuex
State
Get Vuex state in Vue component
mapState helper function
Getter
Accessed via properties
Access via method
mapGetters auxiliary function
Mutation
Submit payload
Action
Home Web Front-end JS Tutorial Installation and use of Vue.js state management mode Vuex (code example)

Installation and use of Vue.js state management mode Vuex (code example)

Sep 01, 2018 pm 04:44 PM
javascript vue.js vuex

The content of this article is about the installation and use of Vue.js state management mode Vuex (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

Installation and use of Vue.js state management mode Vuex (code example)

uex is a state management pattern developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way.

Installing and using vuex

First we install vuex in the vue.js 2.0 development environment:

npm install vuex --save
Copy after login

Then, add:

import vuex from 'vuex'
Vue.use(vuex);
const store = new vuex.Store({//store对象
    state:{
        show:false,
        count:0
    }
})
Copy after login

to main.js and then Then, add the store object when instantiating the Vue object:

new Vue({
  el: '#app',
  router,
  store,//使用store
  template: '<app></app>',
  components: { App }
})
Copy after login

Now, you can obtain the state object through store.state and trigger state changes through the store.commit method:

store.commit('increment')

console.log(store.state.count) // -> 1
Copy after login

State

Get Vuex state in Vue component

The easiest way to read the state from the store instance is to return a certain state in the calculated property:

// 创建一个 Counter 组件
const Counter = {
  template: `<p>{{ count }}</p>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}
Copy after login

mapState helper function

When a component needs to obtain multiple states, declaring these states as computed properties will be somewhat repetitive and redundant. In order to solve this problem, we can use the mapState auxiliary function to help us generate calculated properties:

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}
Copy after login

When the name of the mapped calculated property is the same as the name of the child node of state, we can also pass a string array to mapState :

computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])
Copy after login

Getter

Getters are similar to computed in vue. They are used to calculate state and then generate new data (state). Just like calculated properties, the return value of getter will It is cached based on its dependencies and will only be recalculated when its dependency values ​​change.

Getter accepts state as its first parameter:

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})
Copy after login

Accessed via properties

The Getter is exposed as a store.getters object, and you can access these values ​​as properties :

store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Copy after login

Getter can also accept other getters as the second parameter:

getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

store.getters.doneTodosCount // -> 1
Copy after login

Used in components:

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}
Copy after login

Note that getters are used as Vue when accessed through properties Part of a reactive system is caching.

Access via method

Access via method

You can also pass parameters to the getter by letting the getter return a function. It is very useful when you query the array in the store:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
Copy after login
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
Copy after login

Note that when the getter is accessed through a method, it will be called every time without caching the results.

mapGetters auxiliary function

mapGetters auxiliary function just maps the getters in the store to local calculated properties:

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
Copy after login

If you want to give a getter property another name, Use object form:

mapGetters({
  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})
Copy after login

Mutation

The only way to change the state in the Vuex store is to submit a mutation.

Registration:

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})
Copy after login

Call:

store.commit('increment')
Copy after login

Submit payload

You can pass in additional parameters to store.commit, that is, mutation Payload:

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
Copy after login
store.commit('increment', 10)
Copy after login

If multiple parameters are submitted, they must be submitted in the form of objects

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
Copy after login
store.commit('increment', {
  amount: 10
})
Copy after login

Note: The operations in mutations must be synchronous;

Action

Action is similar to mutation, except that

  • Action submits a mutation instead of directly changing the state.

  • Action can contain any asynchronous operation.

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})
Copy after login

Action is triggered through the store.dispatch method:

store.dispatch('increment')
Copy after login

Execute asynchronous operations inside the action:

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}
Copy after login

Pass parameters in object form:

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})
Copy after login

Related recommendations:

Vue.js of vuex (state management)

How to use Vuex state management

About Vuex’s family bucket status management

The above is the detailed content of Installation and use of Vue.js state management mode Vuex (code example). 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 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 implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles