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

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

使用function():
export default {
  mounted: function() {
    this.socket = 'something'
    console.log('mounted')
  },
  methods: {
    submitMessage() {
      console.log(this.socket) // something
    }
  }
}

有任何想法吗?

最佳答案

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

10-06 04:42