While trying Vue.js I encountered in a thing I don’t know how to do: filter a part of a Json file.
Let me explain better:
I’m using a file Json full of electronics products like computers, mouse, keyboards ecc… I would like to show them as categories:
-Computers
computers here…
-Peripherals
peripherals here…
-Monitors
monitors here…
-Ecc…
Now, to show the products i created a file "Card.vue":
<script setup>
import { defineProps } from "vue"
const { product } = defineProps(["product"])
import {RouterLink} from "vue-router"
</script>
<template>
<div class="card col-4 text-center center">
<RouterLink :to="product.ref + product.id">
<!-- -->
<div class="img">
<img :src="product.img" alt="">
</div>
<div class="card-text">
<h2>{{ product.name }}</h2>
<p>{{ product.description }}</p>
</div>
</RouterLink>
</div>
</template>
<style scoped>
.card{
overflow: hidden;
border-radius: 0%;
/* margin-right: 5px;
margin-bottom: 5px; */
box-shadow: 1px 1px 10px red;
cursor: pointer;
}
.card .img{
width: 300px;
height: 300px;
margin: 0;
}
.card img{
width: 100%;
height: 100%;
}
.center{
display: flex;
align-items: center;
justify-content: center;
}
</style>
And then for the main page i created "HomeView.vue".
Now I’m stuck here. I don’t know how to use the with some type of filters…
I tryed something like this: <Card v-for="(prod, type) in product" v-if="type=='computer'" :key="prod.id" :product="prod"/>
This is a template of my file Json:
{
"id": 1,
"name": "Computer number 1",
"price": 1699.99,
"type": "computer"
},
{
"id": 8,
"name": "Microphone",
"price": 79.99,
"type": "peripherals"
},
{
"id": 11,
"name": "Monitor 75hz",
"price": 129.99,
"type": "monitor"
}
Thakn you!
>Solution :
Try avoiding using v-for and v-if on the same element. In most cases a simple filter will result in the same output but needs less computing power.
It’s not entirely clear what you are trying to achieve but an example of your list could be:
<Card v-for="(prod, type) in product.filter(p => p.type === 'computer')"
:key="prod.id"
:product="prod"/>