skip to Main Content

One simple question:

Can Vue’s data function be asynchronous?

For example, if I want to get some data from the API in Vue by using some library which offers only async methods, such as axios, and if I want to load that data into Vue’s data function, is there a way to do it?

Here is what I talk about:

import axios from "@/axios"
export default {
    async data() {
        return {
            a: await axios.get("http://localhost:1/getA"),
        }
    }
}

This compiles but this.a is always undefined.
If I remove async it does not compile anymore.
If I remove await this.a is still undefined even if I wait for several minutes after loading the component before checking the value of this.a.
If I remove both async and await then I get the value in this.a, just that value is not what it should be in a, but a Promise object instead.

Of course that I know that I can use a method to initialize the a, but, this question is only theoretical, because I want to know whether data in Vue can be async or not without using an initialization method.

2

Answers


  1. According to the Vue documentation, the data method in a Vue component should return an object.

    interface ComponentOptions {
      data?(
        this: ComponentPublicInstance,
        vm: ComponentPublicInstance
      ): object
    }
    

    However, if you wrap the data with async, it returns a promise that encapsulates the object. As a result, Vue doesn’t recognize the appropriate type to handle reactivity.

    To address this issue, you can take a practical approach by using an async method to fetch the data and store it in your component’s local state. This approach allows you to handle the asynchronous nature of data fetching while maintaining reactivity. As mentioned by @deceze in the comments, this is a recommended solution.

    Login or Signup to reply.
  2. you can call async method in the mounted state of the component to get all the data that you want and store it in the data variable that you declare before then after you can refer to the data variable as you want

    export default{
        data(){
         return {
          datavariable:[],
        }
      },
      methods:{
         async getData(){
            const responce = await axios.get("http://localhost:1/getA");
            this.datavariable=responce.data;
          }
        }
       mounted(){
        this.getData();
      }
    }
    

    after this you can use the variable where ever you want in that specific component but to make the data global you have to setup a global state management system called store and read more about it in this link: state management in vuejs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search