I think it is better to split the axios commands and the vue components.
This is my directory structure:
src
api
- products.js
components
- Products.vue
products.js
import axios from 'axios';
const listProducts = () => {
const headers = { "Content-Type": "application/json" };
let url = "http://localhost:8001/api/v1/products";
const response = axios.get(url, headers);
return response.data
}
export default {
listProducts,
}
Products.vue
:
<template>
<div>{{ products }}</div>
</template>
<script>
import { listProducts } from "@/api/products.js"
export default {
data () {
return {
products: {},
}
},
created() {
this.getProducts();
},
methods: {
getProducts() {
this.products = listProducts();
}
}
}
</script>
But this.products
is undefined. I tried some stuff with async and await, but nothing works.
And what would be best practice in vue3?
CodePudding user response:
axios.get()
returns a Promise
, so response
in the following line is actually a Promise
(not the Axios response itself):
const listProducts = () => {
⋮
const response = axios.get(url, headers);
return response.data // ❌ `response` is a `Promise`
}
To get the response, you can await the result of the axios.get()
call: