在 Vuex getter 中使用组件道具的正确方法是什么?

What is the correct way to use component props in a Vuex getter?

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

Here is the whole thing on webpackbin.

有点像 vuex git repo 中的基本计数器示例。但是你想使用 vuex getter 和通过组件上的 属性 传递的 ID,你会怎么做?

getter必须是纯函数,所以不能使用this.counterId。官方文档说你必须使用计算的 属性,但这似乎也不起作用。此代码 returns 未定义 getter:

import * as actions from './actions'

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

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] 
  }
}