我需要在用户离开路线并要求确认之前显示一个模态。基于该确认,用户可以离开路线。问题是确认是作为一个承诺来的,而 OnBeforeRouteLeave
期望一个布尔值返回,而我在 .then()
中无法做到这一点。我在他们的 API 上找不到任何东西,但有没有我可以使用的方法?像 next()
在以前版本的 vue 路由器中工作,或者更适合这种情况的钩子?
onBeforeRouteLeave((to, from, next) => {
if(!isEqual(store.getters['product/getProduct'], initialState)) {
Swal.fire({
title: 'You want to leave the page?',
text: `There are unsaved changes that will be lost.`,
icon: 'warning',
showCancelButton: true,
buttonsStyling: false,
cancelButtonColor: '#d33',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Yes, leave!',
customClass: {
confirmButton: "btn font-weight-bold btn-light-primary",
cancelButton: "btn font-weight-bold btn-light-primary",
},
heightAuto: false
}).then((result) => {
if (result.isConfirmed) {
store.commit('product/resetState')
next()
}
})
}
return false
})
更新:
在源代码上它说:
<块引用>添加导航守卫,当当前位置的组件即将离开时触发。类似于 beforeRouteLeave 但可以在任何组件中使用。卸下组件时,防护罩将被移除。
在 beforeRouteLeave
上有一个 next
函数,但是当我使用它时,我得到:
未捕获(承诺)错误:导航守卫无效
答案 0 :(得分:1)
onBeforeRouterLeave()
有这个 signature:
export declare function onBeforeRouteLeave(leaveGuard: NavigationGuard): void
它有一个 void
返回类型,这意味着不需要返回。
问题似乎是您的导航守卫仅在满足 next()
条件时才调用 if
,但在 next()
情况下也应该调用 else
:
onBeforeRouteLeave((to, from, next) => {
if(!isEqual(store.getters['product/getProduct'], initialState)) {
Swal.fire(/*...*/)
.then(() => {
next()
})
} else {
next()
}
})