Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

312
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda