Pet*_*ada 4 vue-router vuejs3 vue-composition-api vue-router4
我需要在用户离开路线并要求确认之前显示模式。基于该确认,用户可以离开路线。问题是确认作为一个承诺而来,并OnBeforeRouteLeave期望一个布尔值返回,而我无法在.then(). 我在他们的 API 上找不到任何内容,但是有我可以使用的方法吗?就像next()之前版本的 vue router 中的那样,或者可能是更适合这种情况的钩子?
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
})
Run Code Online (Sandbox Code Playgroud)
更新:
源代码上写着:
添加一个导航防护,只要当前位置的组件即将离开,该防护就会触发。与 beforeRouteLeave 类似,但可以在任何组件中使用。拆卸组件时,防护罩将被移除。上面
beforeRouteLeave有一个next函数,但当我使用它时,我得到:
未捕获(承诺)错误:无效的导航防护
onBeforeRouterLeave()有这个签名:
Run Code Online (Sandbox Code Playgroud)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()
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14067 次 |
| 最近记录: |