假设您有一个简单的应用程序组件,其中包含一个按钮,可以使用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 }
},
}
答案 0 :(得分:4)
getter应该是纯函数,而不依赖于组件状态。
你仍然可以从getter创建一个计算过的prop,或者直接使用store:
//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]
}
}