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?
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:
๐
const listProducts = async () => {
โฎ ๐
const response = await axios.get(url, headers);
return response.data
}
Similarly, this updated listProducts()
function now returns a Promise
because it's async
. Your component now must await the result of listProducts()
:
// Products.vue
export default {
โฎ
methods: {
๐
async getProducts() {
๐
this.products = await listProducts();
}
}
}