我需要使用 AJAX 调用的结果来初始化 Vue 组件的数据。我尝试了以下方法:
data: function () {
return {
supplierCount: 0
}
},
created: function () {
axios.get("/supplier/list").then(response => {
this.supplierCount = response.data.length;
});
}
但是,这种方法不起作用,因为模板可以在 AJAX 处理程序更新 supplierCount
之前访问数据。
用异步调用的结果初始化数据的正确方法是什么?例如,如果我从 data
返回一个 promise(而不是一个对象),Vue 会等到 promise 被拒绝/解决后再将数据暴露给模板吗?
最佳答案
我认为您不能强制您的组件仅在 ajax 调用之后才初始化,但是您可以将其配置为在加载 ajax 数据之前隐藏,方法是使用 css (使用 v-show
) 或简单地阻止其呈现(使用 v-if
)。
例如,您可以将属性 hasLoaded
添加到您的组件,并将 v-show
或 v-if
绑定(bind)到它,像这样:
在你的 js 上:
data: function () {
return {
supplierCount: 0,
hasLoaded: false
}
},
created: function () {
axios.get("/supplier/list").then(response => {
this.supplierCount = response.data.length;
this.hasLoaded = true;
});
}
在您的模板上:
<!-- The top element is your root element, and you should always render it, so the v-show is appended to the immediate child -->
<div>
<div v-show="hasLoaded">
<!-- the rest of your template goes here -->
</div>
</div>
关于javascript - 使用 AJAX 调用的结果初始化 Vue 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58729860/