[英]Filter product by checkbox vue js
我正在嘗試在 laravel 中使用 vue js 實現復選框過濾器,但它沒有按預期工作。 對於第一個復選框 All ,當我選中和取消選中復選框時,它可以工作並顯示/隱藏所有產品。 但對於 Tech、Entertainment 和 Fictional,它不會根據點擊的復選框過濾產品。
<template>
<div class="container">
<div class="row ">
<div class="col-md-4">
<div class="filter">
<label><input type="checkbox" v-model="selectedCategory" value="0" /> All</label>
<label><input type="checkbox" v-model="selectedCategory" value="1" /> Tech</label>
<label><input type="checkbox" v-model="selectedCategory" value="2" /> Entertainment</label>
<label><input type="checkbox" v-model="selectedCategory" value="3" /> Fictional</label>
</div>
</div>
</div>
<div class="col-md-8">
<div class="card" v-for="product in filteredProduct">
<div class="card-header">{{product. name}}</div>
<div class="card-body">
<img :src="product.image">
<p>{{product.price}}</p>
<p>{{product.category_id}}</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data:function(){
return {
products:[],
selectedCategory: ["0"],
}
},
computed: {
filteredProduct: function() {
var app = this;
var category = app.selectedCategory;
console.log(category)
if(category.includes("0")) {
return app.products;
} else {
return app.products.filter(function(p) {
return category.includes(p.category_id);
});
}
}
},
mounted() {
console.log('Product mounted.')
var app = this;
axios.get('/products')
.then(function (resp) {
app.products = resp.data;
})
.catch(function (resp) {
console.log(resp);
alert("Could not load");
});
}
}
</script>
任何幫助,將不勝感激
我的猜測是products
數組中的category_id
類型為number 。 但是, selectedCategory
數組具有字符串格式的數字。 includes
使用嚴格相等來檢查提供的值是否存在於數組中。 這就是它適用於"0"
原因,因為它是作為字符串提供的。 如果將其更改為p.category_id.toString()
,它將起作用:
這是一個工作片段:
new Vue({ el: '#app', data: function() { return { products: [{ category_id: 1, name: "Tech 1" }, { category_id: 1,name: "Tech 2"},{ category_id: 2, name: "Entertainment 1" },{ category_id: 3, name: "Fictional 1" }], selectedCategory: ["0"], } }, computed: { filteredProduct: function() { const app = this, category = app.selectedCategory; if (category.includes("0")) return app.products; else return app.products.filter(p => category.includes(p.category_id.toString()) ); } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div class="container" id="app"> <div class="row "> <div class="col-md-4"> <div class="filter"> <label><input type="checkbox" v-model="selectedCategory" value="0" /> All</label> <label><input type="checkbox" v-model="selectedCategory" value="1" /> Tech</label> <label><input type="checkbox" v-model="selectedCategory" value="2" /> Entertainment</label> <label><input type="checkbox" v-model="selectedCategory" value="3" /> Fictional</label> </div> </div> </div> <div class="col-md-8"> <div class="card" v-for="product in filteredProduct"> <div class="card-header">{{product. name}}</div> </div> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.