使用vue中的复选框过滤列表项

时间:2018-10-28 11:42:58

标签: vue.js vuejs2 vue-component

我有一些简单的列表项和过滤器面板codesandbox

<template>
  <div id="filter">
    <h1>Filter List</h1>

    <div class="filter-panel">
      <ul class="filter-list">
        <li :key="index" v-for="(ch, index) in checkboxOptions">
          <label>
            <input 
              type="checkbox" 
              v-model="ch.selected" 
               :value="ch.value">
            <span> {{ ch.text }} </span>
          </label>
        </li>
      </ul>
      <hr>
      <ul class="filter-list">
        <li :key="index" v-for="(r, index) in radioOptions">
          <label>
            <input 
              type="radio" 
              v-model="selected" 
               :value="r.value">
            <span> {{ r.text }}</span>
          </label>
        </li>
      </ul>
    </div>


    <transition-group name="fade" mode="out-in" tag="ul" class="catalog-list">
      <li :key="index" v-for="(item, index) in filterItems">
        <h3>{{ item.name }}</h3>
        <span>{{ item.price }}</span>
      </li>
    </transition-group>

  </div>
</template>

<script>

export default {
  name: "FilterList",
  data() {
    return {
      items: [
        { name: "Name 1", price: "200" },
        { name: "Name 2", price: "100" },
        { name: "Name 3", price: "5" }
      ],
      selected: "all",
      radioOptions: [
        { text: 'All', value: 'all' },
        { text: 'Filter Name 1', value: 'Name 1' },
        { text: 'Filter Name 2', value: 'Name 2' },
        { text: 'Filter Name 3', value: 'Name 3' }
      ],
      checkboxOptions: [
        { text: 'Filter 200', value: '200', selected: false },
        { text: 'Filter 100', value: '100', selected: false },
        { text: 'Filter 5', value: '5', selected: false }
      ]
    };
  },
  computed: {
    filterItems() {
      var vm = this,
          name = vm.selected;

          //console.log(vm.checkboxOptions.value);

      if(name === "all"){
        return vm.items;
       } else {
         return this.items.filter(function(n){
          return n.name === name;
        });
       }      
    }
  }
};
</script>

过滤器面板包括:input[type="radio"]input[type="checkbox"]。按名称和价格过滤。

按名称过滤单选按钮即可。我无法获得selected的复选框,无法按价格值过滤商品。

问题:如何使用单选和复选框输入来过滤项目列表?如何使用复选框过滤价格?

1 个答案:

答案 0 :(得分:2)

您没有在过滤器功能中使用选定的复选框值。您可以使用:

  computed: {
    filterItems() {
      var vm = this,
          name = vm.selected;

          console.log(name);
      var currentItems = vm.items;
      if (name !== 'all') {
         currentItems = currentItems.filter(function(n){
          return n.name === name;
        });
      }
      vm.checkboxOptions.forEach(option => {
        if (option.selected) {
          currentItems = currentItems.filter(item => item.price === option.value)
        }
      })
      return currentItems;      
    }
  }