locnguyen
locnguyen

Reputation: 841

Vue - How to access data inside beforeRouteLeave - In Component Guard

Trying to access data inside beforeRouteLeave but everything is undefined

Code below

<template>
  ...
</template>

<style lang="scss">
  ...
</style>

<script>

  export default {
    name: 'blog-new',
    data() {
      return {
        isBodyChanged: false,
        isPublished: false,
        isTitleChanged: false,
      }
    },
    created() {
      ...
    },
    beforeRouteLeave: (to, from, next) => {
      console.log(this.isBodyChanged) //<--undefined
      if (this.isBodyChanged) {
        return next(false)
      } else {
        return next()
      }
    }
  }
</script>

Upvotes: 1

Views: 2286

Answers (3)

DEV-Jacol
DEV-Jacol

Reputation: 607

for me i Change lib from

"vue-router": "^2.0.1"

to

"vue-router": "^3.0.1"

version 2 has error: https://github.com/vuejs/vue-router/issues/1288

Upvotes: 0

zivce
zivce

Reputation: 464

Just as Dominic said. Also you should add your function in methods.

Upvotes: 0

Dominic Serrano
Dominic Serrano

Reputation: 114

You need to use an ES5 function instead of an arrow function. Using an ES5 function will make the this keyword equal to the instance of the component, whereas an arrow function uses lexical scoping.

beforeRouteLeave: function(to, from, next) {
  if (this.isBodyChanged) {
    return next(false)
  } else {
    return next()
  }
}

However, you can also use this shorthand which I find helpful. This evaluates to the same as above.

beforeRouteLeave(to, from, next) {
  if (this.isBodyChanged) {
    return next(false)
  } else {
    return next()
  }
}

Upvotes: 4

Related Questions