Reputation: 468
I'm having problems with rendering some data fetched from an API. Even though the data is empty using the v-if condition, empty divs are in the DOM.
<template>
<div class="product" v-for="products in jsonData" :key="products.title">
<div class="product-item" v-if="products.city==city||city=='all'">
<div>{{products.title}}</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Product',
props: ['city'],
data() {
return {
jsonData: ''
}
},
mounted() {
let url = 'http://localhost:8080/data/products.json'
axios.get(url)
.then(res => {
console.log(res.data)
this.jsonData = res.data
})
.catch(err => {
console.log(err);
})
}
}
</script>
Since v-for has a higher directive than v-if, I can't seem to find a solution to completely remove empty divs.
For example, if products.city == 'Seattle', it renders the products available in Seattle. But in the DOM, all products are being loaded, so the classes for .product are being stashed in the DOM.
Thanks, appreciate the help.
Upvotes: 0
Views: 1356
Reputation: 692
I don't have enough reputation to comment on answer above, so i open another answer.
The jsonData.filter is not a function is probably throwed by default jsonData value which is string, string is not an array, so .filter is undefined. If jsonData supposed to be an array, default value of jsonData should be declared as empty array.
Btw, to achieve what u want, you can use computed of vue to filter data u want, then use the computed filteredJSONData to render. Below is the code.
<template>
<div class="product" v-for="products in filteredJsonData" :key="products.title">
<div class="product-item">
<div>{{products.title}}</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Product',
props: ['city'],
data() {
return {
jsonData: []
}
},
computed: {
filteredJsonData() {
return this.city==='all' ? this.jsonData : this.jsonData.filter(
products => products.city===this.city
)
}
},
mounted() {
let url = 'http://localhost:8080/data/products.json'
axios.get(url)
.then(res => {
console.log(res.data)
this.jsonData = res.data
})
.catch(err => {
console.log(err);
})
}
}
</script>
Upvotes: 2