【问题标题】:Which is the best way to filter data from an array with Vue JS?使用 Vue JS 从数组中过滤数据的最佳方法是什么?
【发布时间】:2019-10-30 13:30:03
【问题描述】:

我正在寻找最佳做法。

我从我的 API 获得了这个产品列表:

[
    {
        "id": 6,
        "name": "Pechuga de pollo",
        "category": "Chicken",
        "existencia": 100
    },
    {
        "id": 7,
        "name": "Pierna de pavo",
        "category": "Chicken",
        "existencia": 100
    },
    {
        "id": 8,
        "name": "Lonja de pescado",
        "category": "Fish",
        "existencia": 200
    },
    {
        "id": 9,
        "name": "Coca Cola",
        "category": "Soda",
        "existencia": 200
    },
    {
        "id": 10,
        "name": "Jugo de naranja",
        "category": "Juice",
        "existencia": 200
    }
]

所以我需要通过值“鸡”过滤这个产品数组。

我试过 filter() 方法,效果很好。


this.chickenProducts =productList.filter(product=>product.category=="Chicken")

然后我使用带有 chickenProducts 数组的 v-for 指令来填充仅包含鸡肉产品的选择输入。

考虑到 Vue JS 中的条件,您知道另一种从数组中过滤数据以填充选择输入的方法吗? 我还在练习 Vue。

【问题讨论】:

  • 为什么需要另一种方式?
  • 只是想知道是否还有其他最好的方法。
  • 最好的方法不止一种
  • 你在哪里存储chickenProducts?你能展示更多你的代码吗? API 调用和选择,也许?

标签: javascript arrays object vue.js ecmascript-6


【解决方案1】:

计算过滤器数组? 对了,我记得Vue1可以在v-for中使用filterBy,但是Vue2把它去掉了。

【讨论】:

    【解决方案2】:

    您的实施方式有点严格。如果您想更改过滤条件怎么办?还是您的代码中有多个条件?

    如果我是你,我会创建一个方法,根据传入的条件返回一个数组。我迭代了那个结果。这在维护和可扩展性方面更加直接和模块化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 2011-01-20
      • 2015-02-27
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 2023-03-30
      相关资源
      最近更新 更多