Vue计算的属性返回了承诺?

时间:2019-02-06 23:37:15

标签: javascript laravel vue.js vuejs2 computed-properties

我有一个计算属性,可以触发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;
}

当页面加载时,我在那里的调试器会捕获并拥有我希望看到的所有数据(变量json是一个数组,其中包含我的项)。

但是当我查看Vue Dev工具中的Vue组件时,它只是说:

ingredients:Promise

我一直在工作时使用相同的结构,但是我无法弄清楚这有什么不同。如果在浏览器中点击API路由,则会看到预期的JSON。

我正在像这样迭代它:

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

但是正如ingredients此处所指的是Promise一样,该表未呈现。

我不确定是否很重要,但是我正在使用Vue / Laravel混合。 Laravel方面运行正常,API调用返回了我期望的URL。

1 个答案:

答案 0 :(得分:0)

这里的原因是,在对promise和getter进行操作时,计算的属性在promise完成后实际上不会更新-因此,在此处使用vuex分派或任何其他promise均无效。

如果您在created()生命周期内触发函数,则应该执行该操作。此外,如果您需要能够动态更改配方,则可以设置观察者以捕获任何更新。

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

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

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