[Vuejs]-Change Computed Property on Click

1👍

You just need to store the category in data and then you can use the filter dynamically.

here as a working example with a cat array that checks if the category is included.

new Vue({
  el: "#app",
  name: 'Food',
  data() {
    return {
      cat: ['fruit','candy'],
      foods: [
        { name: 'banana', category: 'fruit' },
        { name: 'orange', category: 'fruit' },
        { name: 'strawberry', category: 'fruit' },
        { name: 'gum', category: 'candy' },
        { name: 'fuzzy peach', category: 'candy' },
      ]
    }
  },
  computed: {
    filtered: function() {
      var cat = this.cat;
      return this.foods.filter(function(food) {
        return cat.indexOf(food.category) >= 0;
      })
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>


<div id="app">
  <div class="layout">
    <button @click="cat=['fruit', 'candy']">all</button>
    <button @click="cat=['fruit']">fruit</button>
    <button @click="cat=['candy']">candy</button>
    <div v-for="food in filtered" :key="food.name" class="card">
      <p>{{ food.name }}</p>
    </div>
  </div>
</div>
👤Daniel

Leave a comment