Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - Calling an asynchronous method inline

I would like to use a method to make an API call in a v-for loop, the purpose is to load an object based on a UID.

My method looks like this:

methods: {
  async getTodo(uid) {
  const data = await axios.get(
    "https://jsonplaceholder.typicode.com/todos/" + uid
  );
  return data;
}

}

From my understanding you can include methods inline as such:

{{ getTodo(2) }}

However this always returns [object Promise]

I must have misunderstand the use of methods for this purpose, or the async call in the method itself is incorrect — if anyone can clarify what is wrong here.

like image 953
ogot Avatar asked Apr 08 '26 12:04

ogot


1 Answers

You can store the asynchronous response in a reactive array when the promise returns. Since it's reactive, the promise response will automatically be displayed once each promise return.

Do something like:

export default {
  data: {
    asyncDataHolder: []
  },
  methods: {
    async getTodo(uid) {
    const data = await axios.get(
      "https://jsonplaceholder.typicode.com/todos/" + uid
    );
    let index = asyncDataHolder.length + 1;
    asyncDataHolder.$set(index, data);
}

And inside your v-for loop:

{{asyncDataHolder[i]}}
like image 186
andreybleme Avatar answered Apr 11 '26 02:04

andreybleme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!