how can i display a prop in filteredProducts when fetching data using axios. i have passed through a prop like below.
export default {
data() {
return {
filteredProducts: [],
};
},
mounted() {
axios
.get('/src/stores/sneakers.json')
.then(response => { const products = response.data
this.filteredProducts = products.filter(product => product.name.includes('Nike'))
})
},
computed: {
resultCount () {
return Object.keys(this.filteredProducts).length
},
},
props: {
brand: {
type: Object,
},
},
I would like to replace 'Nike' with brand.name as that is being passed through. Much appreciated
CodePudding user response:
export default {
data() {
return {
products: [],
};
},
mounted() {
/* it would be better if you can move this API call to a method */
axios
.get('/src/stores/sneakers.json')
.then(response => {
this.products = response.data ?? [];
})
},
computed: {
resultCount () {
return this.filteredProducts?.length ?? 0
},
brandName() {
return this.brand?.name ?? "";
},
filteredProducts () {
return this.products?.filter(
product => product.name?.toLowerCase()?.includes(this.brandName.toLowerCase())
)
},
},
props: {
brand: {
type: Object,
},
},
}
CodePudding user response:
Choose the products that are named 'Nike' and pass them into filteredProducts
. After that you can change the names using a computed property and use that in the template.
<template>
<div
v-for="(item, i) in nikeProducts"
:key="i"
>
</div>
</template>
<script>
export default {
props: {
brand: {
type: Object
}
}
data() {
return {
filteredProducts: [],
};
},
mounted() {
axios
.get('/src/stores/sneakers.json')
.then(response => {
const products = response.data
this.filteredProducts = products.filter(product => product.name.include('Nike'));
})
},
computed: {
nikeProducts() {
return this.filteredProducts.map(product => product.name = this.brand.name)
}
}
}
</script>