【发布时间】:2016-11-21 03:16:07
【问题描述】:
假设您有一个简单的应用程序组件,其中包含一个按钮,可以使用 vuex 商店从计数器组件中添加多个计数器。
Here is the whole thing on webpackbin.
有点像vuex git repo中的基本反例。但是你想使用带有通过组件上的属性传递的ID的vuex getter,你会怎么做?
getter 必须是纯函数,所以不能使用this.counterId。官方文档说您必须使用计算属性,但这似乎也不起作用。此代码为 getter 返回 undefined:
import * as actions from './actions'
export default {
props: ['counterId'],
vuex: {
getters: {
count: state => state.counters[getId]
},
actions: actions
},
computed: {
getId() { return this.counterId }
},
}
【问题讨论】:
-
您的代码似乎是正确的。 “getId”计算属性背后的想法是让您使用组件中的属性,而不是状态。在你的情况下,你正在做这两件事。没有错,但在调用 getId() 时要注意你的逻辑以及从中得到什么。
-
id 只是数组索引。计算属性本身工作正常。尽管 getter 仍然返回 undefined ,所以一定有问题。我正在使用计算属性,因为根据定义,您不能在 getter 中使用
this。
标签: javascript vue.js vuex