Jam*_*art 5 javascript laravel vue.js computed-properties vuejs2
我有一个触发 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;
}
Run Code Online (Sandbox Code Playgroud)
我在那里的调试器在页面加载时捕获并包含我希望看到的所有数据(变量json是一个数组,其中包含我的项目)。
但是当我查看 Vue Dev 工具中的 Vue 组件时,它只是说:
ingredients:Promise
我一直在工作中使用相同的结构,但我无法弄清楚这有什么不同。如果我在浏览器中点击 API 路由,我会看到预期的 JSON。
我正在迭代它,例如:
<tr v-for="(ingredient, index) in ingredients" :key="index">
但是因为ingredients这里只是指一个 Promise,所以表格没有被渲染。
我不确定这是否重要,但我使用的是 Vue/Laravel 组合。Laravel 端工作正常,API 调用返回到我期望的 URL 中。
这里的原因是,计算属性在 Promise 完成后实际上不会更新,因为它们对 setter 和 getter 进行操作 - 因此在这里使用 vuex 调度或任何其他 Promise 将不起作用。
如果您在生命周期中触发函数,created()那么应该可以做到。此外,如果您需要能够动态更改配方,您可以设置一个观察者来捕获任何更新。
data: () => ({
ingredients: null,
})
watch: {
ingredients(nexVal, preVal) {
// do some stuff here
}
}
created() {
this.ingredients = myAsyncCallForIngredients()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4355 次 |
| 最近记录: |