Vue - 如何访问 beforeRouteLeave 中的数据 - 在 Component Guard 中

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

正在尝试访问 beforeRouteLeave 中的数据,但一切都是 undefined

下面的代码

<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>

您需要使用 ES5 函数而不是箭头函数。使用 ES5 函数将使 this 关键字等于组件的实例,而箭头函数使用 lexical scoping.

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

不过,您也可以使用我认为有用的 shorthand。这与上面的计算结果相同。

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

正如多米尼克所说。您还应该在 methods.

中添加您的功能

对我来说,我更改了库 来自

"vue-router": "^2.0.1"

"vue-router": "^3.0.1"

版本 2 有错误: https://github.com/vuejs/vue-router/issues/1288