I am new to vue js and i have this component, i am trying to make another API call on click of one of the list options.
<template>
<div>
<h1 >Our Product</h1>
<ul >
<li @click="handleClick(1)">Clothes</li>
<li @click="handleClick(5)">Shoes</li>
<li @click="handleClick(2)">Watches</li>
<li @click="handleClick(4)">Furniture</li>
</ul>
<div >
<div v-for="store in stores" :key="store.category.id">
<div >
<img :src="store.images[0]" alt="img" />
</div>
</div>
</div>
</div>
</template>
<script>
import { computed, ref, watch } from "vue";
import Clothes from "../Products/Clothes.vue";
import Shoes from "../Products/Shoes.vue";
import axios from "axios";
export default {
components: {
Clothes,
Shoes,
},
props: [],
data() {
return {
stores: [],
errors: [],
product: ref(1), //Where product is the changeable value
};
},
methods: {
handleClick(params) {
this.product = params;
console.log(this.product);
},
},
//Here is the Api call.
async created() {
await axios
.get(
`https://api.escuelajs.co/api/v1/categories/${this.product}/products`
)
.then((res) => {
this.stores = res.data;
console.log(this.stores);
})
.catch((e) => {
console.log(this.errors.push(e));
});
},
I want that when i click for a particular product it changes to the number i inserted, Thanks
CodePudding user response:
Don't use
ref
when you use the option api, you're mixin up option api and composition api (thesetup
function)Move your api call to a method and call it from both
created
andhandleClick
export default {
components: {
Clothes,
Shoes,
},
data() {
return {
product: 1,
stores: [],
errors: [],
};
},
methods: {
fetchProduct(productId) {
return axios.get(`https://api.escuelajs.co/api/v1/categories/${productId}/products`)
.then((res) => {
this.stores = res.data;
})
.catch((e) => {
this.errors.push(e);
console.error(e);
});
},
handleClick(productId) {
this.product = productId;
this.fetchProduct(productId);
},
},
//Here is the Api call.
async created() {
await this.fetchProduct(this.product);
},
};
CodePudding user response:
You need to wait for sync call :
const app = Vue.createApp({
data() {
return {
product: 1,
stores: [],
errors: [],
};
},
methods: {
async fetchProduct(productId) {
await axios.get(`https://api.escuelajs.co/api/v1/categories/${productId}/products`)
.then((res) => {
this.stores = res.data;
})
.catch((e) => {
this.errors.push(e);
console.error(e);
});
},
handleClick(productId) {
this.product = productId;
this.fetchProduct(productId);
},
},
async created() {
await this.fetchProduct(this.product);
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.2/axios.min.js" integrity="sha512-QTnb9BQkG4fBYIt9JGvYmxPpd6TBeKp6lsUrtiVQsrJ9sb33Bn9s0wMQO9qVBFbPX3xHRAsBHvXlcsrnJjExjg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
<button @click="handleClick(3)">get productid 3</button>
{{stores}}
</div>