为什么在 mounted
中使用 () =>
和 function()
结果不同:
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
}
}
}
有什么想法吗?
最佳答案
您不应该使用箭头函数来定义生命周期钩子(Hook)、方法、...(例如 mounted: () => this.socket++
)。原因是箭头函数绑定(bind)了父上下文,所以 this 将不是您期望的 Vue 实例,this.socket
将是未定义的。
关于vue.js - Vue/Nuxt - 安装 : () => Vs mounted: function(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46388873/