在 Vue 中,通常使用 that = this 的场景是在回调函数中需要访问 Vue 实例的属性或方法时,由于回调函数中的 this 指向的是回调函数本身,而不是 Vue 实例,因此可以先将 this 保存到一个变量 that 中,然后在回调函数中使用 that 来访问 Vue 实例。
以下是一个示例代码:
export default {
data() {
return {
message: 'Hello, Vue!'
}
},
methods: {
showMessage() {
// 在 setTimeout 回调函数中访问 this.message 会报错
setTimeout(function() {
console.log(this.message) // undefined
}, 1000)
// 使用 that = this 将 this 保存到变量中
const that = this
setTimeout(function() {
console.log(that.message) // Hello, Vue!
}, 1000)
}
}
}
在上面的代码中,showMessage 方法中使用了 setTimeout 函数来模拟异步操作,由于回调函数中的 this 指向的是回调函数本身,因此在回调函数中访问 this.message 会报错。为了解决这个问题,我们使用 that = this 将 this 保存到变量 that 中,并在回调函数中使用 that.message 来访问 Vue 实例中的 message 属性。
需要注意的是,在 Vue 3 中,可以使用箭头函数来避免 that = this 的问题,因为箭头函数的 this 指向的是定义时的上下文,而不是运行时的上下文加粗样式。因此,在 Vue 3 中,可以这样写:
export default {
data() {
return {
message: 'Hello, Vue!'
}
},
methods: {
showMessage() {
setTimeout(() => {
console.log(this.message) // Hello, Vue!
}, 1000)
}
}
}
在上面的代码中,我们使用箭头函数来定义 setTimeout 的回调函数,这样就可以直接访问 this.message,而不需要使用 that = this 了。