
export default {
json1:[
['红色','黄色','蓝色'],
['s','m'],
['棉的','涤纶'],
// [100,200,300,400]
],
json2:[
{
color:'红色',
type:'s',
mianliao:'棉的',
price:100
},
{
color:'黄色',
type:'s',
mianliao:'棉的',
price:100
},
{
color:'蓝色',
type:'s',
mianliao:'棉的',
price:100
},
{
color:'黄色',
type:'s',
mianliao:'涤纶',
price:200
},
{
color:'蓝色',
type:'m',
mianliao:'涤纶',
price:400
},
]
}
<template>
<div>
<div
class="goods-row"
v-for="(itemArr, rowIndex) in mockData.json1"
:key="rowIndex"
>
<template v-for="(filter, i) in itemArr">
<div
class="btn"
:class="{active: condition[filters[rowIndex]]===filter}"
:key="i"
@click="changeFilter(rowIndex, filter)"
:title="filter"
>
{{ filter }}
</div>
</template>
</div>
<hr />
条件 {{ condition }}
<hr />
商品内容:
<div v-if="showGoods">
<div v-for="(item, index) in showGoods" :key="index">
{{ item }}
</div>
</div>
</div>
</template>
<script>
import mockData from "@/data.js";
function _diff(obj1, obj2) {
if (!obj1 || !obj2) {
throw new Error("参数缺失");
}
if (typeof obj1 !== "object" || typeof obj2 !== "object") {
throw new Error("参数类型错误");
}
if (obj1 === obj2) return true;
for (let key in obj1) {
if (obj1.hasOwnProperty(key) && key !== "price") {
//都有的属性 但是值不同
if (obj1[key] && obj2[key]) {
if (obj1[key] !== obj2[key]) {
return false;
}
}
}
}
return true;
}
export default {
data() {
return {
mockData: mockData,
condition: {},
filters: [],
};
},
computed: {
showGoods() {
if (mockData.json2) {
return mockData.json2.filter((ele) => {
return _diff(this.condition, ele);
});
} else {
return [];
}
},
},
created() {
let first = this.mockData.json2[0];
for (let key in first) {
this.filters.push(key);
// 默认选中 condition 需要和第一个数据的值一致
// this.condition[key]=this.first[key]
this.$set(this.condition, key, "");
}
},
methods: {
changeFilter(index, content) {
// switch(i){
// case 0:
// this.condition.color=content
// break
// case 1:
// this.condition.type=content
// break
// case 2:
// this.condition.mianliao=content
// break
// default:
// break
// }
if (this.condition[this.filters[index]] === content) {
this.condition[this.filters[index]] = "";
} else {
this.condition[this.filters[index]] = content;
}
},
},
};
</script>
<style scoped>
.goods-row {
display: flex;
justify-content: center;
align-items: center;
}
.btn {
max-width: 160px;
width: 80px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
height: 40px;
line-height: 40px;
border: 1px solid grey;
border-radius: 4px;
margin: 8px;
cursor: pointer;
text-align: center;
}
.active.btn {
background: orange;
color: #fff;
}
</style>