简体   繁体   中英

Vue computed property returning a promise?

I have a computed property that triggers an API call and returns the data:

async ingredients() {
    const url = "/api/ingredients";

    const request = new Request(url, {
      method: "GET",
      credentials: "same-origin"
    });

    const response = await fetch(request);
    const json = await response.json();
    //debugger;
    return json;
}

The debugger I have in there catches when the page is loading and has all the data that I expect to see (variable json is an array with my items inside it).

But when I look at the Vue component in the Vue Dev tools, it just says:

ingredients:Promise

I use this same structure at work all the time, but I can't figure out what's different about this. If I hit the API route in my browser, I see the expected JSON.

I'm iterating over it like:

<tr v-for="(ingredient, index) in ingredients" :key="index">

But as ingredients here just refers to a Promise, the table isn't rendered.

I'm not sure it matters but I'm using a Vue/Laravel mix. The Laravel side is working completely fine, the API call comes back in the URL I expect.

The reason here is that computed properties won't actually update after the promise is completed as they operate on setters and getters - so using vuex dispatch here or any other promise will not work.

If you trigger your function on created() lifecycle then that should do it. Additionally, if you need to be able to change the recipe dynamically you can set a watcher to catch any updates.

data: () => ({
    ingredients: null,
})

watch: {
    ingredients(nexVal, preVal) {
        // do some stuff here
    }
}

created() {
    this.ingredients = myAsyncCallForIngredients()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM