为什么使用() =>和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
}
}
}
有任何想法吗?
您不应使用箭头功能来定义生命周期挂钩,方法,...(例如
mounted: () => this.socket++)。原因是箭头函数绑定了父上下文,因此这将不是您期望的Vue实例,并且this.socket将是未定义的。