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

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

本文关键字:是什么 方法 组件 getter Vuex      更新时间:2023-09-26

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

以下是webpackbin上的全部内容。

有点像vuex git repo中的基本反例。但是,如果您想使用vuexgetter,它的ID是通过组件上的属性传递的,您将如何做到这一点?

getter必须是一个纯函数,因此不能使用this.counterId。官方文件说你必须使用计算属性,但这似乎也不起作用。此代码为getter返回未定义的:

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

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