In my opinion, it's more efficient to separate the axios commands from the vue components. This is how I structured my directories:
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.fetchProducts();
},
methods: {
fetchProducts() {
this.products = listProducts();
}
}
}
</script>
However, I'm facing an issue where this.products
is undefined. I've experimented with async and await, but to no avail.
What would be the best practice in vue3?