Reputation: 841
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
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
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