【问题标题】:Vue Router Composition API OnBeforeRouteLeave invalid navigation guardVue Router Composition API OnBeforeRouteLeave 无效导航保护
【发布时间】:2023-03-09 14:37:01
【问题描述】:

我需要在用户离开路线并要求确认之前显示一个模式。基于该确认,用户可以离开路线。问题是确认是一个承诺,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-router vuejs3 vue-composition-api vue-router4


    【解决方案1】:

    onBeforeRouterLeave() 有这个signature

    export declare function onBeforeRouteLeave(leaveGuard: NavigationGuard): void
    

    它有一个void返回类型,这意味着不需要返回。

    问题似乎是您的导航守卫仅在满足if 条件时才调用next(),但在else 情况下也应调用next()

    onBeforeRouteLeave((to, from, next) => {
      if(!isEqual(store.getters['product/getProduct'], initialState)) {
        Swal.fire(/*...*/)
          .then(() => {
            next()
          })
      } else {
        next()
      }
    })
    

    demo

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2018-09-12
      • 2022-06-15
      • 2021-01-08
      相关资源
      最近更新 更多