首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >过滤select输入的最佳方式是什么?

过滤select输入的最佳方式是什么?
EN

Stack Overflow用户
提问于 2019-06-12 02:48:15
回答 4查看 186关注 0票数 -1

我从API得到以下响应:

代码语言:javascript
复制
[
    {
        "id": 6,
        "nombre": "Pechuga de pollo",
        "categoria": "Pollo",
        "existencia": 100
    },
    {
        "id": 7,
        "nombre": "Pierna de pavo",
        "categoria": "Pollo",
        "existencia": 100
    },
    {
        "id": 8,
        "nombre": "Lonja de pescado",
        "categoria": "Pescado",
        "existencia": 200
    },
    {
        "id": 9,
        "nombre": "Coca Cola",
        "categoria": "Bebida",
        "existencia": 200
    },
    {
        "id": 10,
        "nombre": "Jugo de naranja",
        "categoria": "Bebida",
        "existencia": 200
    }
]

所以我需要通过值"categoria“来过滤这些json,然后我将在我的模板中填充三个不同的选择输入。

我尝试使用filter()方法,但我想我做错了:

代码语言:javascript
复制
///This is the function that filter needs on the argument:

filtradoBebida(bebida){
             bebida.categoria == "Bebida"
    },

///This is the function where I apply the filter method:

filtrarProductos(){
       this.bebidas = productosLista.filter(filtradoBebida)
 }

我想用json填充select,其中值categoria == "Bebida",其他select输入填充json,值== "Pollo“。

您是否知道通过过滤json的值来填充vuejs中select的另一种方法?

EN

回答 4

Stack Overflow用户

发布于 2019-06-12 02:56:09

您没有正确使用filter

我建议使用ES6 arrow function

代码语言:javascript
复制
///This is the function where I apply the filter method:

filtrarProductos () {
       this.bebidas = productosLista.filter(x => x.categoria === "Bebida")
 }
票数 0
EN

Stack Overflow用户

发布于 2019-06-12 03:00:54

使用computed property。下面是一个可以过滤其items的组件的基本概要

代码语言:javascript
复制
<template>
  <ul>
    <li v-for="item in filteredItems" :key="item.id">{{ item.text }}</li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      // Set this via an API call
      // Here we assume an item has: id, text, category
      items: [],
      // Use this as the v-model for a select
      // Here we assume '' is "no selection"
      category: '',
    };
  },
  computed: {
    filteredItems() {
      // Show all of the items if there is not category filter
      if (this.category === '') return this.items;
      return this.items.filter(item => item.category === this.category);
    },
  },
};
</script>
票数 0
EN

Stack Overflow用户

发布于 2019-06-12 03:02:13

我对filtradoBebida后面的逗号有点迷惑。

它似乎是某个对象中的一个属性。

因此,需要this从该对象内部调用它。

同样,要成为一个正确的过滤谓词,它应该返回一个布尔值。

您的函数总是返回undefined

所以,试一下

代码语言:javascript
复制
filtradoBebida(bebida){
             return bebida.categoria == "Bebida"
    },

///This is the function where I apply the filter method:

filtrarProductos(){
       this.bebidas = productosLista.filter(this.filtradoBebida)
 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56550035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档