This time I will bring you a detailed explanation of the use of mapState and mapGetters in vuex. What are the precautions for using mapState and mapGetters in vuex. The following is a practical case, let's take a look.
1. Introduce the four kings in vuex: State, Mutations, Actions, Getters
(I remember the notes about vuex last time: http: //www.jb51.net/article/138229.htm, is a simple application; these are some simple vue widget methods: http://www.jb51.net/article/138230.htm)
What are the Four Diamonds?
1.State (this can be lowercase state, consistent with the official website, in uppercase, because of personal habits, the following code introduction is in lowercase)
The state management of vuex needs to rely on it The state tree, the official website says:
Vuex uses a single state tree - yes, one object contains all application-level states. It now exists as a "Single Source of Data (SSOT)". This also means that each application will only contain one store instance. A single state tree allows us to directly locate any specific piece of state and easily obtain a snapshot of the entire current application state during debugging.
Simple and rough understanding: We need to put the amount of state management we need here, and then move it in subsequent operations
Let’s declare a state:
const state = {
blogTitle: '迩伶贰blog',
views: 10,
blogNumber: 100,
total: 0,
todos: [
{id: 1, done: true, text: '我是码农'},
{id: 2, done: false, text: '我是码农202号'},
{id: 3, done: true, text: '我是码农202号'}
]
}
2. Mutation
We have a state tree. If we want to change its state (value), we must use vue to specify the only method mutation. The official website says:
The only way to change the state in the Vuex store is to submit a mutation. Mutation in Vuex is very similar to events: each mutation has a string event type (type) and a callback function (handler).
Simple and rough understanding: Any change in the value of state without mutation is a rogue (illegal)
Let’s do a mutation:
const mutation = {
addViews (state) {
state.views++
},
blogAdd (state) {
state.blogNumber++
},
clickTotal (state) {
state.total++
}
}
3. Action
The role of action is consistent with the role of mutation. It submits mutation and thereby changes state. It is an enhanced version of changing state. The official website says:
Action is similar to mutation , the difference is:
Action submits a mutation instead of directly changing the state.
Action can contain any asynchronous operation.
Simple and crude understanding: Well, that’s pretty much the summary, let’s understand it this way!
Let’s take an action:
const actions = {
addViews ({commit}) {
commit('addViews')
},
clickTotal ({commit}) {
commit('clickTotal')
},
blogAdd ({commit}) {
commit('blogAdd')
}
}
4. Getter
The official website says: Sometimes we need to derive some states from the state in the store , such as filtering a list and counting. Reduce our operations on these state data
Simple and rough understanding: The data on the state tree is more complicated. When we use it, we need to simplify the operation. The state.todos above is an object. Choose different ones in the component. When receiving data, it needs to be processed, so that it needs to be processed once every time. We simplify the operation, process it in the getter, and then export a method; (well, it seems to be complicated)
Let’s get a getter:
const getters = {
getToDo (state) {
return state.todos.filter(item => item.done === true)
// filter 迭代过滤器 将每个item的值 item.done == true 挑出来, 返回的是一个数组
}
}
2. Use
It’s useless to learn, it’s useless, we have to use it:
1. Create a new file under src
We create a new store under the src folder under the project (vue-cli scaffolding), and create a new index.js file under this store. Fill in the above code, as shown below:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
blogTitle: '迩伶贰blog',
views: 10,
blogNumber: 100,
total: 0,
todos: [
{id: 1, done: true, text: '我是码农'},
{id: 2, done: false, text: '我是码农202号'},
{id: 3, done: true, text: '我是码农202号'}
]
}
const actions = {
addViews ({commit}) {
commit('addViews')
},
clickTotal ({commit}) {
commit('clickTotal')
},
blogAdd ({commit}) {
commit('blogAdd')
}
}
const mutations = {
addViews (state) {
state.views++
},
blogAdd (state) {
state.blogNumber++
},
clickTotal (state) {
state.total++
}
}
const getters = {
getToDo (state) {
return state.todos.filter(item => item.done === true)
// filter 迭代过滤器 将每个item的值 item.done == true 挑出来, 返回的是一个数组
}
}
export default new Vuex.Store({
state,
actions,
mutations,
getters
})
// 将四大金刚挂载到 vuex的Store下
2, main.js import file
import Vue from 'vue'
import App from './App'
import router from './router/router.js'
// 引入 状态管理 vuex
import store from './store'
// 引入elementUI
import ElementUI from 'element-ui'
// 引入element的css
import 'element-ui/lib/theme-chalk/index.css'
// 引入font-awesome的css
import 'font-awesome/css/font-awesome.css'
// 引入自己的css
import './assets/css/custom-styles.css'
Vue.config.productionTip = false
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<app></app>',
components: { App }
})
Please pay attention to the bold part, not the bold part Part of it is to import other project functions
3. Use
in the component. First enter the component code:
<template>
<p>
</p>
<h4 id="vuex的状态管理数据">vuex的状态管理数据</h4>
<h5 id="博客标题">博客标题</h5>
<i>
{{this.$store.state.blogTitle}}
</i>
<h5 id="todos里面的信息">todos里面的信息</h5>
<ul>
<li>
<span>{{item.text}}</span> <br>
<span>{{item.done}}</span>
</li>
</ul>
<h5 id="初始化访问量">初始化访问量</h5>
<p>
mapState方式 {{viewsCount}};<br>
直接使用views {{this.$store.state.views}}
</p>
<h4 id="blogNumber数字">blogNumber数字 </h4>
<span>state中blogNumber:{{this.$store.state.blogNumber}}</span>
<h4 id="总计">总计</h4>
<span>state中total:{{this.$store.state.total}}</span>
<p>
<button>点击增加total</button>
</p>
</template>
<style>
</style>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
data () {
return {
checked: true
}
},
created () {
// this.$store.dispatch('addViews') // 直接通过store的方法 触发action, 改变 views 的值
this.blogAdd() // 通过mapActions 触发mutation 从而commit ,改变state的值
},
computed: {
...mapState({
viewsCount: 'views'
}),
...mapGetters({
todosALise: 'getToDo' // getToDo 不是字符串,对应的是getter里面的一个方法名字 然后将这个方法名字重新取一个别名 todosALise
})
},
methods: {
...mapMutations({
totalAlise: 'clickTotal' // clickTotal 是mutation 里的方法,totalAlise是重新定义的一个别名方法,本组件直接调用这个方法
}),
...mapActions({
blogAdd: 'blogAdd' // 第一个blogAdd是定义的一个函数别名称,挂载在到this(vue)实例上,后面一个blogAdd 才是actions里面函数方法名称
})
} } </script>
mapState, mapGetters, mapActions, mapMutations
These names are an auxiliary function corresponding to the four kings,
a).mapState, the official website says:
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:
对于官网给出的例子,截个图,供学习,详情请进官网:https://vuex.vuejs.org/zh-cn/state.html , 我记录下官网说的少的 ...mapState() 方法

vue 现在好多例子,都是用es6 写的,es6中增加了好多神兵利器,我们也得用用。我们也要用‘对象展开运算符',这个具体的用法,请参考具体的学习资料,我们主要讲讲 ...mapState({...}) 是什么鬼。
下面实例代码中:
html:
<p>
mapState方式 {{viewsCount}};<br>
直接使用views {{this.$store.state.views}}
</p>
js:
...mapState({
viewsCount: 'views'
}),
我们需要使用一个工具函数将多个对象合并为一个,这个 ... 方法就合适了,将多个函数方法合并成一个对象,并且将vuex中的this.$store.views
映射到this.viewsCount (this -> vue)上面来,这样在多个状态时可以避免重复使用,而且当映射的值和state 的状态值是相等的时候,可以是直接使用
...mapState({
'views'
}),
b).mapMutations 其实跟mapState 的作用是类似的,将组件中的 methods 映射为 store.commit 调用
上面的代码:
html:
<span>{{this.$store.state.total}}</span>
<p>
<button>点击增加total</button>
</p>
js:
...mapMutations({
totalAlise: 'clickTotal' // clickTotal 是mutation 里的方法,totalAlise是重新定义的一个别名方法,本组件直接调用这个方法
})
c). mapActions, action的一个辅助函数,将组件的 methods 映射为 store.dispatch 调用
上例代码:
html:
<h4 id="blogNumber数字">blogNumber数字 </h4>
<span>state中blogNumber:{{this.$store.state.blogNumber}}</span>
js:
方法调用:
created () {
// this.$store.dispatch('blogAdd') // 直接通过store的方法 触发action, 改变 views 的值
this.blogAdd() // 通过mapActions 触发mutation 从而commit ,改变state的值
},
方法定义:
...mapActions({
blogAdd: 'blogAdd' // blogAdd是定义的一个函数别名称,挂载在到this(vue)实例上,blogAdd 才是actions里面函数方法名称 })
d). mapGetter 仅仅是将 store 中的 getter 映射到局部计算属性:
html:
<h5 id="todos里面的信息">todos里面的信息</h5>
- //
- 这里就是直接读取store的值,没有做过滤操作,如果需要过滤。
还需要单独写方法操作
{{item.text}}
{{item.done}}
js:
...mapGetters({
todosALise: 'getToDo' // getToDo 不是字符串,对应的是getter里面的一个方法名字 然后将这个方法名字重新取一个别名 todosALise
}),
这个 getToDo 是在getters 定义的一个方法,它将todos 里的对象属性done为true的之过滤出来
getToDo (state) {
return state.todos.filter(item => item.done === true)
// filter 迭代过滤器 将每个item的值 item.done == true 挑出来, 返回的是一个数组
}
上面代码操作后的效果截图:

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of the use of mapState and mapGetters in vuex. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.
The Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AMThe latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function







