javascript 将密钥传递到vuex getter以获取不同的状态

6uxekuva  于 2023-02-15  发布在  Java
关注(0)|答案(3)|浏览(136)

在vuex存储中有许多类似的状态:

const state = {
  count: 0,
  count2: 1,
  count3: 2
};

并且对于每个状态都有一个相应的吸气器:

const getters = {
  getCount: (state) => state.count,
  getCount2: (state) => state.count2,
  getCount3: (state) => state.count3,
};

有没有办法把这3个放在一个动态的getter中,这个getter会接受这个键并得到相应的数据。

b4wnujal

b4wnujal1#

您可以创建另一个getter,并使用另一个函数传递参数。

const getters = {
  getCount: (state) => state.count,
  getCount2: (state) => state.count2,
  getCount3: (state) => state.count3,
  // The param could be "count" || "count2"
  getAllCount: (state) => (param) =>  state[param] 
  // and calling
  this.$store.getters['getAllCount'](theParamKey)
};
jum4pzuy

jum4pzuy2#

你有两种选择,首先,你可以从getter as explained here返回一个函数,或者,在很多情况下,你可以只改变状态并返回一个对象(或数组):

const state = {
  count: {
    count1: 0,
    count2: 1,
    count3: 2,
  }
};
const getters = {
  getCount: (state) => state.count,
};

根据我的经验,第二种选择通常是最好的,因为它对其他开发人员和维护来说更容易(从getter返回函数是非常违反直觉的),而且因为它超级容易处理对象(或数组),但肯定第一种选择也有它的用例。

nimxete2

nimxete23#

我们有一种方法可以将参数传递给getters函数。

const getters = {
  getCount: (state) => (arg) => {
    return state[arg]; // where arg can be count or count1 or count2
  }
}

参考链接:www.example.comhttps://vuex.vuejs.org/guide/getters.html#method-style-access

相关问题