首页 > 解决方案 > 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功能,但是当我使用它时,我得到:

未捕获(承诺)错误:无效的导航保护

标签: vue-routervuejs3vue-composition-apivue-router4

解决方案


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()
  }
})

演示


推荐阅读