


Installation and use of Vue.js state management mode Vuex (code example)
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. .
Installing and using vuex
First we install vuex in the vue.js 2.0 development environment:
npm install vuex --save
Then, add:
import vuex from 'vuex' Vue.use(vuex); const store = new vuex.Store({//store对象 state:{ show:false, count:0 } })
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 } })
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
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 } } }
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 } }) }
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' ])
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) } } })
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 }]
Getter can also accept other getters as the second parameter:
getters: { // ... doneTodosCount: (state, getters) => { return getters.doneTodos.length } } store.getters.doneTodosCount // -> 1
Used in components:
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount } }
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) } }
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
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', // ... ]) } }
If you want to give a getter property another name, Use object form:
mapGetters({ // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount` doneCount: 'doneTodosCount' })
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++ } } })
Call:
store.commit('increment')
Submit payload
You can pass in additional parameters to store.commit, that is, mutation Payload:
// ... mutations: { increment (state, n) { state.count += n } }
store.commit('increment', 10)
If multiple parameters are submitted, they must be submitted in the form of objects
// ... mutations: { increment (state, payload) { state.count += payload.amount } }
store.commit('increment', { amount: 10 })
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') } } })
Action is triggered through the store.dispatch method:
store.dispatch('increment')
Execute asynchronous operations inside the action:
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
Pass parameters in object form:
// 以载荷形式分发 store.dispatch('incrementAsync', { amount: 10 })
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!

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



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

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

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

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