单击更改计算 属性

Change Computed Property on Click

是否可以通过单击事件 add/change 在“v-for”中计算 属性? 我希望能够在单击适当的按钮时显示基于类别的食物列表。

如果我点击“水果”按钮,它将是

 <div v-for="food in fruitCategory" :key="food.name" class="card">
      <p>{{ food.name }}</p>
    </div>

和“糖果”按钮

 <div v-for="food in candyCategory" :key="food.name" class="card">
      <p>{{ food.name }}</p>
    </div>

这是一个好方法吗?

实际代码如下

<template>
  <div class="layout">
    <button>all</button>
    <button>fruit</button>
    <button>candy</button>
    <div v-for="food in foods" :key="food.name" class="card">
      <p>{{ food.name }}</p>
    </div>
  </div>
</template>
export default {
  name: 'Food',
  data() {
    return {
      foods: [
        { name: 'banana', category: 'fruit' },
        { name: 'orange', category: 'fruit' },
        { name: 'strawberry', category: 'fruit' },
        { name: 'gum', category: 'candy' },
        { name: 'fuzzy peach', category: 'candy' },
      ]
    }
  },
  computed: {
    fruitCategory: function() {
      return this.foods.filter(function(food) {
        return food.category === 'fruit'
      })
    }
  },
  candyCategory: function() {
    return this.foods.filter(function(food) {
      return food.category === 'candy'
    })
  }
}

您只需要将类别存储在data中,然后您就可以动态地使用过滤器了。

此处作为工作示例,使用 cat 数组检查类别是否包含。

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>