[英]How can I async await for an event in a child component? Vue-router
I want to protect the user from navigating away from an unsaved form using a custom modal and vue-router.我想保护用户不要使用自定义模式和 vue-router 离开未保存的表单。
This is possible with native browser alert box这可以通过本机浏览器警报框实现
beforeRouteLeave (to, from, next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next();
} else {
next(false);
}
}
but how can I wait for an event from a custom child modal component?但是如何等待来自自定义子模态组件的事件?
async beforeRouteLeave(to, from, next) {
const a = await this.showModal();
if (a) {
next();
} else {
next(false);
}
}
beforeRouteLeave
isn't promise-aware, a promise that async
function returns is ignored. beforeRouteLeave
不支持承诺, async
function 返回的 promise 将被忽略。
next
is a common name for a callback in JavaScript ecosystem. next
是 JavaScript 生态系统中回调的通用名称。 As the documentation shows, it accepts an argument.如文档所示,它接受一个参数。 It should be:
它应该是:
async beforeRouteLeave(to, from, next) {
const a = await this.showModal();
if (a)
next();
else
next(false);
}
Got it working but not convinced this is the best solution:得到它的工作,但不相信这是最好的解决方案:
First, save the next
function as a data object首先将
next
function保存为数据object
beforeRouteLeave (to, from, next) {
if (this.$store.state.product.unsavedChanges) {
this.nextObj = next; // save next function as a data object
this.showModal = true;
} else {
next();
}
}
then in your modal component, emit an event and handle it on your parent component然后在您的模态组件中,发出一个事件并在您的父组件上处理它
<modal @continueOrCancel="continueOrCancel" />
Fire the function on your parent component在父组件上触发 function
methods: {
continueOrCancel(e) {
if (e == "continue") {
this.nextObj(); // works.
} else {
this.nextObj(false); // does not work. Only logs the next function. Also tried with string "false", and 0 which produces the same result.
this.showModal = false; // continue, but what about route lifecycle ??
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.