vue-router - Vue Router Composition API OnBeforeRouteLeave 无效导航保护
问题描述
在用户离开路线并要求确认之前,我需要显示一个模式。基于该确认,用户可以离开路线。问题是确认是作为一个承诺来的,并且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
功能,但是当我使用它时,我得到:
未捕获(承诺)错误:无效的导航保护
解决方案
onBeforeRouterLeave()
有这个签名:
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()
}
})
推荐阅读
- python - 登录系统(无 GUI)给出错误的输出
- javascript - MERN:刷新加载原始数据
- reactjs - OMdb react props.data.map 不是函数
- python - 点击只显示不正确选项名称的第一个字符(错误:没有这样的选项:)
- r - 我如何找到低于 R 标准的频率数量?
- python - int 类型的 value_counts() 操作错误
- assertj - 在自定义断言类中重用 AssertJ 可迭代差异验证器
- python - 当我通过 cmd 运行 pip 命令时,出现错误
- android - Android按钮视图绑定ClickListener不起作用
- android - 为什么设置 maxHeight 和 minHeight 时需要设置 layout_height