在vue-router中,如何使用beforeLeave

时间:2017-11-30 01:53:44

标签: vue-router

我希望在一个组件离开之前完成一些信息验证。

我已经扫描了vue-router文档:https://router.vuejs.org

但我在我的文件中使用vue-cli:router1.vue,

console.log(this.$router.beforeLeave) -> undefined

我该如何使用它?

1 个答案:

答案 0 :(得分:2)

将此添加到您的router1.vue

export default {
  //...
  beforeRouteLeave (to, from, next) {
    // called when the route that renders this component is about to
    // be navigated away from.
    // has access to `this` component instance.
  },
  //...
}

例如:

beforeRouteLeave (to, from , next) {
  const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
  if (answer) {
    next()
  } else {
    next(false)
  }
}

在这条路线离开之前它会被召唤。

参考:https://router.vuejs.org/en/advanced/navigation-guards.html