Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

311
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!