假设您有一个简单的应用程序组件,其中包含一个按钮,可以使用vuex商店从计数器组件添加多个计数器。
Here is the whole thing on webpackbin.
有点像vuex git repo.But中的基本计数器示例,您希望将vuex getter与通过组件上的属性传递的ID一起使用,您将如何做到这一点?
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 }
},
}发布于 2016-07-19 00:00:01
getters应该是纯函数,不依赖于组件状态。
您仍然可以从getter创建计算道具,或者直接使用存储:
//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]
}
}https://stackoverflow.com/questions/38437992
复制相似问题