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

Chr*_*ris 3 javascript vue.js vuex

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

这是 webpackbin 上的全部内容。

有点像vuex git repo 中的基本计数器示例。但是你想使用 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 }
    },
}
Run Code Online (Sandbox Code Playgroud)

Lin*_*org 6

getter 应该是纯函数而不依赖于组件状态。

你仍然可以从 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] 
  }
}
Run Code Online (Sandbox Code Playgroud)