简体   繁体   English

Vue 计算属性返回承诺?

[英]Vue computed property returning a promise?

I have a computed property that triggers an API call and returns the data:我有一个触发 API 调用并返回数据的计算属性:

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).我在那里的调试器在页面加载时捕获并包含我希望看到的所有数据(变量json是一个包含我的项目的数组)。

But when I look at the Vue component in the Vue Dev tools, it just says:但是当我查看 Vue Dev 工具中的 Vue 组件时,它只是说:

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.如果我在浏览器中点击 API 路由,我会看到预期的 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.但由于这里的ingredients只是指一个 Promise,所以表格没有被渲染。

I'm not sure it matters but I'm using a Vue/Laravel mix.我不确定这是否重要,但我使用的是 Vue/Laravel 组合。 The Laravel side is working completely fine, the API call comes back in the URL I expect. Laravel 端工作正常,API 调用返回到我期望的 URL 中。

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.这里的原因是计算属性在 promise 完成后实际上不会更新,因为它们对 setter 和 getter 进行操作 - 因此在这里使用 vuex dispatch 或任何其他 promise 都不起作用。

If you trigger your function on created() lifecycle then that should do it.如果您在created()生命周期上触发您的函数,那么应该这样做。 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()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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