我想使用一个下拉列表来过滤我的JSON数据,并在匹配下拉列表选项时显示不同的JSON数据项。到目前为止,我已经设法将其获取,以便当有人从下拉菜单中选择一项时运行功能,但是我不确定为什么过滤器不起作用,因为我在控制台或WebStorm中未收到任何错误
这是我的代码和JSON数据的示例:
<template>
<b-container id="product-list">
<b-row>
<b-col>
<div>
<b-dropdown id="ddown4" text="Product Type" class="m-md-2">
<b-dropdown-item @click="FilterProducts" v-model="selectedCategory">4.5</b-dropdown-item>
<b-dropdown-item @click="FilterProducts" v-model="selectedCategory">10.5</b-dropdown-item>
</b-dropdown>
</div>
</b-col>
</b-row>
<hr>
<b-row>
<b-col md="4" v-for="product in Products">
<img class="img-fluid" :src="product.image"/>
<h5>{{ product.product_name }} </h5>
<p class="original-price strikethrough">£{{ product.original_price }}</p>
<p>£{{ product.final_price }}</p>
</b-col>
</b-row>
</b-container>
</template>
<script>
import Axios from "axios";
export default {
name: 'Products',
data() {
return {
Products: null,
selectedCategory: ''
}
},
mounted() {
Axios.get('/products.json')
.then(response => (this.Products = response.data.data))
},
methods: {
FilterProducts() {
var vm = this;
var category = vm.selectedCategory;
if(category === '') {
return vm.Products;
} else {
return vm.Products.filter(function(product) {
return product.attributes.tog === category;
});
}
}
}
}
</script>
JSON数据示例:
"data": [
{
"id": "83",
"product_name": "TV",
"category": "Clearance",
"original_price": "139.0000",
"final_price": "105.0000",
"attributes": {
"size": "260x220",
"tog": "10.5 tog"
}
"url": "/tv"
}
答案 0 :(得分:7)
您的计算方法对selectedCategory
是有反应的,不需要像使用@click
那样调用v-model
。
<template>
<b-container id="product-list">
<b-row>
<b-col>
<div>
<b-dropdown id="ddown4" text="Product Type" class="m-md-2">
<b-dropdown-item v-model="selectedCategory">4.5</b-dropdown-item>
</b-dropdown>
</div>
</b-col>
</b-row>
<hr>
<b-row>
<b-col md="4" v-for="product in filteredProducts">
<img class="img-fluid" :src="product.image"/>
<h5>{{ product.product_name }} </h5>
<p class="original-price strikethrough">£{{ product.original_price }}</p>
<p>£{{ product.final_price }}</p>
</b-col>
</b-row>
</b-container>
</template>
<script>
import Axios from "axios";
export default {
name: 'Products',
data() {
return {
Products: null,
selectedCategory: ''
}
},
mounted() {
Axios.get('/products.json')
.then(response => (this.Products = response.data.data))
},
computed: {
filteredProducts() {
if(this.selectedCategory === '') {
return this.Products;
} else {
const category = this.selectedCategory;
return this.Products
.filter((product) => product.attributes.tog === category)
}
}
}
}
</script>