为什么使用结果不同 () => 和 function() 在里面 mounted
() =>
function()
mounted
export default { mounted: () => { this.socket = 'something' console.log('mounted') }, methods: { submitMessage() { console.log(this.socket) // undefined } } }
使用 函数() :
函数()
export default { mounted: function() { this.socket = 'something' console.log('mounted') }, methods: { submitMessage() { console.log(this.socket) // something } } }
有什么想法吗?
您不应该使用箭头函数来定义生命周期挂钩、方法等,。。。(例如。 mounted: () => this.socket++ ). 原因是箭头函数绑定父上下文,因此这将不是您期望的Vue实例,并且 this.socket
mounted: () => this.socket++
this.socket