【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);
            }
        }
    });
}

相关推荐

  1. vue函数 this 指向

    2024-03-15 20:44:04       35 阅读
  2. C语言函数指针指针函数函数

    2024-03-15 20:44:04       52 阅读
  3. C# 函数

    2024-03-15 20:44:04       43 阅读
  4. C++ 函数指针函数

    2024-03-15 20:44:04       47 阅读
  5. C 函数指针函数

    2024-03-15 20:44:04       31 阅读
  6. 66.函数指针函数

    2024-03-15 20:44:04       24 阅读
  7. 函数介绍

    2024-03-15 20:44:04       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-15 20:44:04       91 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-15 20:44:04       97 阅读
  3. 在Django里面运行非项目文件

    2024-03-15 20:44:04       78 阅读
  4. Python语言-面向对象

    2024-03-15 20:44:04       88 阅读

热门阅读

  1. C++ 预编译头文件

    2024-03-15 20:44:04       42 阅读
  2. Excel百万数据如何导入导出

    2024-03-15 20:44:04       39 阅读
  3. 将PostgreSQL插件移植到openGauss指导

    2024-03-15 20:44:04       32 阅读
  4. 【TypeScript】快速掌握TypeScript的基本语法

    2024-03-15 20:44:04       42 阅读
  5. 2024年集创赛FPGA紫光同创赛道男女声,童声变声

    2024-03-15 20:44:04       40 阅读
  6. 蓝桥杯刷题--python-21

    2024-03-15 20:44:04       36 阅读
  7. python中什么是装饰器

    2024-03-15 20:44:04       38 阅读