如何解决Vue / Nuxt,异步等待,Promise在RouteLeave之前触发时,使用Promise询问子组件并等待返回答案
上的完整演示环境问题是我需要定义一个自定义对话框以在用户离开页面时进行确认。
该演示显示了两个页面,分别是index
和question
。只有question
页会遇到beforeRouteLeave
挑战。 beforeRouteLeave
是一个async
函数,用于触发自定义对话框打开,并await
的结果是如果true
会让用户离开。
page / index.vue
no special rules
page / question.vue
<template>
...
<nuxt-link to="/">Go to home</nuxt-link>
<leaveWarning v-if="leaveLightbox" @returnApproval="leaveWindowReturn"/>
<!-- @returnApproval is the child component emitted the result that user click yes or no to leave -->
...
</template>
<script>
import leaveWarning from "~/components/leaveWarning.vue"
export default{
components: {
leaveWarning,...
},data: () => ({
leaveLightbox: false
}),async beforeRouteLeave(to,from,next) {
let approval = await this.launchLeaveWindow();
this.$set(this,"leaveLightbox",false);
if (approval) {
next();
} else {
next(false);
}
},methods: {
launchLeaveWindow() {
return new Promise((resolve,reject) => {
this.$set(this,true);
resolve(this.leaveWindowReturn());
});
},leaveWindowReturn(payload) {
return new Promise((resolve,reject) => {
console.log("payload: " + payload);
if (payload) {
resolve(true);
} else if (payload === false) {
resolve(false);
}
});
}
},}
</script>
components / leaveWarning.vue
将返回$emit("returnApproval",boolean)
<template>
<section class="lightbox" @click.self="closeLeaveWindow">
<div class="container">
<h2>Leave Now?</h2>
<p>Are you sure to leave? The data will lose when leave now.</p>
<div>
<div class="button" @click="approveLeave">Yes</div>
<div class="button" @click="closeLeaveWindow">No</div>
</div>
</div>
</section>
</template>
<script>
export default {
data: () => ({}),methods: {
closeLeaveWindow() {
console.log("clicked: no")
this.$emit("returnApproval",false);
},approveLeave() {
console.log("clicked: yes")
this.$emit("returnApproval",true);
}
}
};
</script>
问题是launchLeaveWindow
调用了方法beforeRouteLeave
,无法等待带有返回布尔值的leaveWindowReturn
。这意味着promise不能一直等待子组件发出结果。
我希望在触发beforeRouteLeave
时先触发launchLeaveWindow
,然后在触发leaveWindowReturn
时等待结果。最后,使用从leaveWindowReturn
到beforeRouteLeave
的返回值来验证重定向挑战。
有解决问题的主意吗?抱歉,我是Promise的新手。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。