vue回调函数中的 this 指向上
问题:方法中添加uni.showModal就无法获取this.currentTime数值
onClickClock(content, type) {
console.log(this.currentTime);
uni.showModal({
title: '提示',
content,
success: function(res) {
if (res.confirm) {
debugger;
const time = this.currentTime;
console.log(this.currentTime);
}
}
});
}
解决问题
在这段代码中,问题出现在回调函数中的 this 指向上。在 JavaScript 中,当你在一个回调函数中使用 this 关键字时,它的值可能会发生变化,取决于函数被调用的方式。
this 在 uni.showModal() 的 success 回调函数中不再指向外层的函数作用域,而是指向 uni.showModal() 函数本身。因此,在回调函数中,this.currentTime 实际上是 undefined,导致 const time = this.currentTime; 报错。
为了解决这个问题,在进入 uni.showModal() 函数之前将 this 赋值给另一个变量,然后在回调函数中使用该变量来访问外部作用域的 this。
onClickClock(content, type) {
const self = this; // 将外部作用域的 this 赋值给变量 self
console.log(self.currentTime);
uni.showModal({
title: '提示',
content,
success: function(res) {
if (res.confirm) {
const time = self.currentTime;
console.log(self.currentTime);
}
}
});
}