• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

234
Vistas
How to split axios functions and components in vue3?

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?

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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();
     }
   }
}

demo

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda