[Vuejs]-How can i add range in vue-filter

2๐Ÿ‘

โœ…

I guess what you want is this:

<label><input type="radio" v-model="filterPrice" value="false"> All Price</label>

<label><input type="radio" v-model="filterPrice" value="true"> Filter Price</label>
<input type="input" v-model.number="minPrice" value="100" :disabled="filterPrice!=='true'"> -
<input type="input" v-model.number="maxPrice" value="200" :disabled="filterPrice!=='true'">
filteredRecipes() {
  if (this.filterPrice !== "true") return this.products;
  return this.products.filter(item => {
    return item.price >= this.minPrice && item.price <= this.maxPrice;
  });
}
๐Ÿ‘คyyyy

2๐Ÿ‘

One workaround is to assign a value of the radio as value="100to200".

<label>
  <input type="radio" v-model="price" value="100to200"/>
  100 To 200
</label>

And then we can bind an event @change to get the filtered products.

Live Demo :

new Vue({
  el: '#app',
  data: {
    price: null,
    filteredProducts: [],
    products: [{
        id: 1,
      name: 'Product 1',
      price: 50
    }, {
        id: 2,
      name: 'Product 2',
      price: 105
    }, {
        id: 3,
      name: 'Product 3',
      price: 180
    }, {
        id: 4,
      name: 'Product 4',
      price: 210
    }]
  },
  mounted() {
    this.filteredProducts = structuredClone(this.products)
  },
  methods: {
    getProducts() {
      const priceRange = this.price.split('to');
        this.filteredProducts = this.products.filter(({ price }) => {
         return priceRange[1] ? price > Number(priceRange[0]) && price < Number(priceRange[1]) : price === Number(priceRange[0])
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <label>
    <input type="radio" v-model="price" value="50" @change="getProducts"/>
    50
  </label>
  <label>
    <input type="radio" v-model="price" value="210" @change="getProducts"/>
    210
  </label>
  <label>
    <input type="radio" v-model="price" value="100to200" @change="getProducts"/>
    100 To 200
  </label>
  <br><br>
  <div v-for="product in filteredProducts" :key="product.id">
    <li>{{ product.name }}</li>
  </div>
</div>
๐Ÿ‘คDebug Diva

Leave a comment