【问题标题】:Vue/ Nuxt - mounted: () => Vs mounted: function()Vue/ Nuxt - 挂载:() => VS 挂载:function()
【发布时间】:2018-03-05 11:01:00
【问题描述】:

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

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

有什么想法吗?

【问题讨论】:

标签: vue.js vuejs2 nuxt.js


【解决方案1】:

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

【讨论】:

  • 这是一个很好的答案。但是@laukok 你应该学习和理解 JavaScript 中的箭头函数和关键字 this 绑定概念。以后会对你有很大帮助。 console.log(this)帮我知道this是什么
猜你喜欢
  • 2021-05-08
  • 2021-05-25
  • 1970-01-01
  • 2017-03-15
  • 2020-03-07
  • 2023-04-08
  • 2021-01-09
  • 2018-01-21
  • 2017-03-31
相关资源
最近更新 更多