vuex - 辅助函数学习

简介: 官网文档:https://vuex.vuejs.org/zh-cn/api.html  最底部mapState此函数返回一个对象,生成计算属性 - 当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。

官网文档:

https://vuex.vuejs.org/zh-cn/api.html  最底部

mapState

此函数返回一个对象,生成计算属性 - 当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。mapState可以声明多个

需要在组件中引入:

import { mapState } from 'vuex'

...mapState({ // ... }) 对象展开运算符

 

mapGetters

将store中的多个getter映射到局部组件的计算属性中

组件中引入

import { mapGetters } from 'vuex'

 

组件的computed计算属性中使用

 1 computed: {
 2 
 3     // 使用对象展开运算符将 getter 混入 computed 对象中
 4     ...mapGetters([
 5 
 6     'doneTodosCount',
 7 
 8     'anotherGetter',
 9 
10     // ...
11     ])
12 
13 }

 

或者给getter属性另起个名字:

mapGetters({

    doneCount: 'doneTodosCount'

})

 

mapMutations

将组件中的 methods 映射为 store.commit 调用(需要在根节点注入store)。

组件中引入:

import { mapMutations } from 'vuex'

 

组件的methods中使用:两种方式,传参字符串数组或者对象,

 1 methods: {
 2 
 3     ...mapMutations([
 4 
 5     'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
 6     // `mapMutations` 也支持载荷:
 7     'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
 8     ]),
 9 
10     ...mapMutations({
11 
12         add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
13     })
14 
15 }

 

mapActions

将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

组件中引入:

import { mapActions } from 'vuex'

 

组件的methods中使用:两种方式,传参字符串数组或者对象,

 1 methods: {
 2 
 3     ...mapActions([
 4 
 5     'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
 6     // `mapActions` 也支持载荷:
 7     'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
 8     ]),
 9 
10     ...mapActions({
11 
12         add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
13     })
14 
15 }

 

2018-04-07  17:57:31

目录
相关文章
|
2月前
|
存储 资源调度 JavaScript
学习使用Vuex
【8月更文挑战第5天】学习使用Vuex
44 5
|
3月前
|
存储 缓存 JavaScript
VUEX 的使用学习一
VUEX 的使用学习一
38 0
|
3月前
|
监控 JavaScript
VUEX 使用学习三 : mutations
VUEX 使用学习三 : mutations
22 0
|
5月前
|
存储 JavaScript
vuex的基本用法
Vuex是Vue.js的状态管理库,用于集中存储和管理共享状态。通过创建Vuex store实例,定义`state`(如`count`)和`mutations`(如`increment`),组件可使用`this.$store.state`访问状态,`this.$store.commit`修改状态。当应用复杂时,可将状态分割成带命名空间的模块,如`cart`,组件内通过`this.$store.state.cart`和`this.$store.commit('cart/addItem')`进行访问和修改。
|
5月前
|
JavaScript
深入理解 Vue.js 中的`mapState`辅助函数:简化状态管理的秘密武器(下)
深入理解 Vue.js 中的`mapState`辅助函数:简化状态管理的秘密武器(下)
深入理解 Vue.js 中的`mapState`辅助函数:简化状态管理的秘密武器(下)
|
5月前
|
缓存 JavaScript
vuex的讲解与相关用法
vuex的讲解与相关用法
25 0
|
5月前
|
JavaScript
深入理解 Vue.js 中的`mapState`辅助函数:简化状态管理的秘密武器(上)
深入理解 Vue.js 中的`mapState`辅助函数:简化状态管理的秘密武器(上)
|
11月前
|
存储 资源调度 JavaScript
vuex详细用法
vuex详细用法
44 0
|
存储 JavaScript 前端开发
vuex中的辅助函数
vuex中的辅助函数
|
存储 JavaScript 前端开发
Vuex的学习
Vuex的学习
97 0