Stark
Stark

Reputation: 19

In vue-router, how to use beforeLeave

I want to finish some information verify before one component leave.

I've scanned the vue-router document: https://router.vuejs.org

But I use vue-cli, in my file: router1.vue,

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

How can I use it?

Upvotes: 1

Views: 9014

Answers (1)

wxsm
wxsm

Reputation: 586

Add this to your 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.
  },
  //...
}

for example:

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

And it will be called before this route leave.

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

Upvotes: 8

Related Questions