How to make a filter with a text field

1

I want to use the value of #search as the filter (only the name field of JSON) for v-for .

The text entered in #search and how the filter will actually be indifferent to me, what I really want to know is how I use this result in v-for .

champions:

[
    {
        "champion":{
            "name": "Aatrox",
            "img_url": "http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/Aatrox.png"
        }
    },
    {
        "champion":{
            "name": "Ahri",
            "img_url": "http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/Ahri.png"
        }
    }
]

<div class="container" id="container">
    <div class="form-group">
        <input type="search" id="search" class="form-control" placeholder="Busque por um campeão">
    </div>

    <div class="champion" v-for="champion in champions" :key="champion.champion.name">
        <img class="champion_image" v-bind:src="champion.champion.img_url">

        <div class="champion_title">{{champion.champion.name}}</div>
    </div>
</div>
    
asked by anonymous 29.10.2017 / 20:25

1 answer

2

Here's a suggestion. The important steps are:

  • associates input to data using v-model
  • uses a computed property to give you the filtered array depending on the input value

Example:

const champions = [{
    "champion": {
      "name": "Aatrox",
      "img_url": "http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/Aatrox.png"
    }
  },
  {
    "champion": {
      "name": "Ahri",
      "img_url": "http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/Ahri.png"
    }
  }
];

new Vue({
  el: "#container",
  data: function() {
    return {
      search: '',
      champions: champions
    };
  },
  computed: {
    filteredChampions() {
      if (!this.search) return this.champions;
      return this.champions.filter(el => el.champion.name.includes(this.search));
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script><divclass="container" id="container">
  <div class="form-group">
    <input type="search" v-model="search" class="form-control" placeholder="Busque por um campeão">
  </div>

  <div class="champion" v-for="champion in filteredChampions" :key="champion.champion.name">
    <img class="champion_image" v-bind:src="champion.champion.img_url">

    <div class="champion_title">{{champion.champion.name}}</div>
  </div>
</div>
    
29.10.2017 / 20:55