首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Vuex getter中使用组件属性的正确方法是什么?

在Vuex getter中使用组件属性的正确方法是什么?
EN

Stack Overflow用户
提问于 2016-07-18 21:28:02
回答 1查看 6K关注 0票数 3

假设您有一个简单的应用程序组件,其中包含一个按钮,可以使用vuex商店从计数器组件添加多个计数器。

Here is the whole thing on webpackbin.

有点像vuex git repo.But中的基本计数器示例,您希望将vuex getter与通过组件上的属性传递的ID一起使用,您将如何做到这一点?

getter必须是一个纯函数,所以不能使用this.counterId。官方文档说您必须使用计算属性,但这似乎也不起作用。下面的代码为getter返回undefined:

代码语言:javascript
复制
import * as actions from './actions'

export default {
    props: ['counterId'],
    vuex: {
        getters: {
            count: state => state.counters[getId]
        },
        actions: actions
    },
    computed: {
        getId() { return this.counterId }
    },
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-19 00:00:01

getters应该是纯函数,不依赖于组件状态。

您仍然可以从getter创建计算道具,或者直接使用存储:

代码语言:javascript
复制
//option A
export default {
    props: ['counterId'],
    vuex: {
        getters: {
            counters: state => state.counters
        },
        actions: actions
    },
    computed: {
        currentCounter() { return this.counters[this.counterId] }
    },
}

//option B (better suited for this simple scenario)
import store from '../store'
computed: {
  currentCounter() {  
    return store.state.counters[this.counterId] 
  }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38437992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档