Vue/Nuxt - 已安装:()=>已安装Vs:function()

lau*_*kok 3 vue.js vuejs2 nuxt.js

为什么结果是不同的使用() =>function()mounted:

export default {
  mounted: () => {
    this.socket = 'something'
    console.log('mounted')
  },
  methods: {
    submitMessage() {
      console.log(this.socket) // undefined
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

使用function():

export default {
  mounted: function() {
    this.socket = 'something'
    console.log('mounted')
  },
  methods: {
    submitMessage() {
      console.log(this.socket) // something
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Anh*_*yen 5

您不应该使用箭头函数来定义生命周期钩子,方法,...(例如mounted: () => this.socket++).原因是箭头函数绑定父上下文,因此这不是您期望的Vue实例,并且this.socket将是未定义的.

  • 这是一个很好的答案。但是@laukok 你应该学习和理解 JavaScript 中的箭头函数和关键字 `this` 绑定概念。以后会对你有很大帮助。`console.log(this)` 帮助我知道什么是 `this` (2认同)