前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vuex - 辅助函数学习

vuex - 辅助函数学习

作者头像
xing.org1^
发布2018-05-17 15:38:16
6510
发布2018-05-17 15:38:16
举报
文章被收录于专栏:前端说吧前端说吧

官网文档:

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

mapState

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

需要在组件中引入:

代码语言:javascript
复制
import { mapState } from 'vuex'

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

mapGetters

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

组件中引入

代码语言:javascript
复制
import { mapGetters } from 'vuex'

组件的computed计算属性中使用

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

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

代码语言:javascript
复制
mapGetters({

    doneCount: 'doneTodosCount'

})

mapMutations

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

组件中引入:

代码语言:javascript
复制
import { mapMutations } from 'vuex'

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

代码语言:javascript
复制
 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):

组件中引入:

代码语言:javascript
复制
import { mapActions } from 'vuex'

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

代码语言:javascript
复制
 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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档