![](/img/trans.png)
[英]Run function inside of another function, but only after ajax has finished
[英]Run one function only when another is finished
如何僅在saveMapAsReceipt()
完成時運行this.$refs.form.submit()
?
HTML:
<form ref="form" ...>
<input @submit.prevent="onSubmit" @click="submit" type="button" name="save" value="Update" class="btn btn-primary btn btn-primary" id="submit-id-save" />
</form>
Vue.js
methods: {
saveMapAsReceipt() {
this.printPlugin.printMap('A4Portrait page', 'Miles');
self = this;
this.routingMap.on('easyPrint-finished', e => {
var reader = new window.FileReader();
reader.readAsDataURL(e.event);
reader.onloadend = function () {
base64data = reader.result;
self.receipt_source = base64data;
}
});
},
submit: function() {
this.saveMapAsReceipt();
this.$refs.form.submit();
},
}
將 Labda 函數傳遞給您的saveMapAsReceipt
方法( closure
),並在您希望閉包執行的位置調用閉包,就像這樣。
methods: {
SaveMapAsReceipt(closure){
this.printPlugin.printMap('A4Portrait page', 'Miles');
self = this;
this.routingMap.on('easyPrint-finished', e => {
var reader = new window.FileReader();
reader.readAsDataURL(e.event);
reader.onloadend = function () {
base64data = reader.result;
self.receipt_source = base64data;
}
closure();
});
},
submit: function() {
let that = this;
this.saveMapAsReceipt(function(){
that.$refs.form.submit();
});
},
}
這是 Promise 應該解決的異步流控制的一個常見問題:
methods: {
async saveMapAsReceipt() {
this.printPlugin.printMap('A4Portrait page', 'Miles');
const e = await new Promise(resolve => this.routingMap.on('easyPrint-finished', resolve));
var reader = new window.FileReader();
reader.readAsDataURL(e.event);
await new Promise(resolve => reader.onloadend = resolve);
this.receipt_source = reader.result;
},
async submit() {
await this.saveMapAsReceipt();
this.$refs.form.submit();
},
}
self = this
是一個錯誤,因為self
指的是一個全局變量。 該構造對於 ES6 箭頭來說是多余的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.