Vue教程21:Vuex Getter

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

该节教程代码可通过npm start运行devServer,在http://localhost:8080/#/index查看效果

Getter的基本使用

代码示例:/lesson21/src/index.js

Vuex中的Getter的作用类似于Vue中的Computed,可以实现在state变化时自动计算出一个新的结果。
在store中配置一个Getter:

getters: {
  count (state) {
    return state.a + state.b
  }
}

代码示例:/lesson21/src/components/Index.vue

在组件Index中,可以通过$store.getters.count就可以读取到相应的值。

<div>count from getters: {{$store.getters.count}}</div>

为了方便使用,通常可以把Getter配置到Computed中:

computed: {
  countFromComputed() {
    return this.$store.getters.count
  }
}

在Template中引用:

<div>count from computed: {{countFromComputed}}</div>

利用Computed更新State

因为Computed属性支持get和set方法,所以能够使用set方法更新State。

首先在Store中设置actions和Mutations。

代码示例:/lesson21/src/store/index.js

mutations: {
  addA (state, n) {
    state.a += n
  },
  addB (state, n) {
    state.b += n
  },
},
actions: {
  addA ({commit}, n) {
    commit('addA', n)
  },
  addB ({commit}, n) {
    commit('addB', n)
  },
},

Index.vue模板中添加<input type=“button” value=“count+5” @click=“addCount(5)” />,调用一个addCount方法,在addCount方法中让countFromComputedSet属性加5。
在computed属性中接收到结果后,将增加的5分配给a属性。

countFromComputedSet: {
  get() {
    return this.$store.getters.count
  },
  set(value) {
    this.$store.dispatch('addA', 5)
  },
},
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值