Vue的methods中定时器的变量报错问题

这是由于this的指向造成的。

普通函数的this谁调用它,它就指向谁,换句话说,普通函数中的this指向是变化的,指向使用函数时的指向。

而箭头函数不同,箭头函数的this指向是固定不变的,指向定义时的指向。

因此,当定时器异步执行时,执行环境已发生了变化,this指向了window,无法找到定义时指向的变量,所以会报错。

错误代码如下:

this.obj = setInterval(function() { // 1秒间隔定时器
	if (this.myTimer.seconds <= 0) {
		clearInterval(this.obj);
	} else {
		this.myTimer.seconds = this.myTimer.seconds - 1;
		this.myTimer.smsBtnText = "倒计时" + this.myTimer.seconds + "秒";
	}
}, 1000); 

正确代码如下:

this.obj = setInterval(() => { // 1秒间隔定时器
	if (this.myTimer.seconds <= 0) {
		clearInterval(this.obj);
	} else {
		this.myTimer.seconds = this.myTimer.seconds - 1;
		this.myTimer.smsBtnText = "倒计时" + this.myTimer.seconds + "秒";
	}
}, 1000);

相关推荐

  1. Vuemethods定时器变量问题

    2023-12-07 04:26:03       60 阅读
  2. 组件使用定时器及销毁问题vue问题

    2023-12-07 04:26:03       61 阅读
  3. Vue3】解决 Props 没有默认值而问题

    2023-12-07 04:26:03       38 阅读

最近更新

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

    2023-12-07 04:26:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-07 04:26:03       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-07 04:26:03       82 阅读
  4. Python语言-面向对象

    2023-12-07 04:26:03       91 阅读

热门阅读

  1. C++ day50 买卖股票最佳时机

    2023-12-07 04:26:03       63 阅读
  2. linux优化-平均负载率

    2023-12-07 04:26:03       57 阅读
  3. 数据结构 / 队列 / 循环队列 / 结构体定义和创建

    2023-12-07 04:26:03       66 阅读
  4. vue的模板语法

    2023-12-07 04:26:03       66 阅读
  5. 使用右值常量进行测试的boost::foreach模块

    2023-12-07 04:26:03       62 阅读
  6. Vue经典面试题源码级分析【一】

    2023-12-07 04:26:03       60 阅读
  7. C#学习相关系列之数组---常用方法使用(二)

    2023-12-07 04:26:03       60 阅读
  8. centos用户相关命令

    2023-12-07 04:26:03       50 阅读
  9. springboot工作原理

    2023-12-07 04:26:03       46 阅读
  10. 联合体union

    2023-12-07 04:26:03       55 阅读