VueJS 如何在继续之前等待 axios 数据
P粉520204081
P粉520204081 2023-08-26 10:34:00
[Vue.js讨论组]
<p>我有这段代码,它应该将数据解析为变量,然后发送一个发布请求。</p> <p>问题是,我需要 API 中的一个属性,但我不知道如何才能等待它返回。</p> <pre class="brush:php;toolbar:false;">addFieldData(data, generatorData) { this.populateModel(data); console.log(this.model); this.$axios.post('data/webform/fields', this.model) .then(res =&gt; { console.log(res); this.$notify({ group: &quot;app&quot;, title: this.$t(&quot;general.success&quot;), text: this.$t(&quot;general.action_has_been_processed&quot;), type: &quot;info&quot; }); }).catch(error =&gt; { this.$notify({ group: &quot;app&quot;, title: this.$t(&quot;general.error&quot;), text: this.$t(&quot;general.error_occured&quot;), type: &quot;error&quot; }); console.log(error); }); }, populateModel(data) { this.model.label = data.label ?? {}; this.model.hint = data.placeholder ?? {}; this.model.attributes = data.attributes ?? {}; this.model.maxlength = data.maxlength ?? 0; this.model.position = this.getFieldPosition(); this.model.required = data.required ?? true; this.model.visible = data.visible ?? true; this.model.disabled = data.disabled ?? false; this.model.style_classes = data.style_classes ?? &quot;&quot;; this.model.model = data.model ?? &quot;&quot;; this.model.default = data.default ?? &quot;&quot;; this.model.input_type = data.input_type ?? &quot;&quot;; this.model.hint = data.hint ?? &quot;&quot;; this.model.help = data.help ?? &quot;&quot;; this.model.type = data.type; }, async getFieldPosition() { const res = await this.$axios.get('/data/webform/' + this.idWebform + '/itemsCount'); this.model.position = res.data.data.count + 1; return res.data.data.count; },</pre> <p>在 addFieldData 中,我调用 populateModel,它应该从 API 获取位置,但在 getFieldPosition 返回数据之前调用 post 请求。</p> <p>我想尝试先等待 getFieldPosition,然后发送 post 请求。</p>
P粉520204081
P粉520204081

全部回复(1)
P粉178132828

首先,您应该拥有 async/await 的所有内容,而无需任何 .then
不要混合它们两者。使用第一个。

然后,在您的 async populateModel 方法中,您应该有一个

this.model.position = await this.getFieldPosition()

因为 getFieldPosition 是异步的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号