How to make a filter with a text field

Asked

Viewed 94 times

1

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

The text inserted in #search and the way the filter is going to be is actually indifferent to me, what I really want to know is how I use this result in the 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>

1 answer

2


Here is a hint. Important steps are:

  • associates the input to data using v-model
  • uses a property computed 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>

<div class="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.