_.debounce防抖函数 在vue中使用this问题,应该传匿名函数而不是箭头函数

简单理解:_.debounce内部做了apply操作,箭头函数由于没有this,无法绑定this,导致最终this是undefined, 而匿名函数,成功通过applay绑定了this,所以this指向了vue组件实例。

methods: {
	// 防抖动
    dSave1: _.debounce(() => {
      console.log(this) // undefined
      this.save()
    }, 500),
    // 防抖动
    dSave2: _.debounce(function(){ 
       console.log('ddd:', this) // this---> vm
    } , 500),
}

debounde函数:
可以看到内部incokeFunc对传入的func做了applay操作(绑定this),而匿名函数function(){}存在this可以被apply成功绑定;反之,因为箭头函数()=>{}本身没有this,所以applay操作无效,因此vue中使用debouncd函数,如果传入箭头函数,其this指向不是vue实例,而是undefined。
在这里插入图片描述
总结:
在使用 lodash.debounce 等方法的时候,为保证 this 正确的指向,回调函数推荐使用 匿名函数(function(){})。
箭头函数根本没有自己的 this,导致内部的 this 就是外层代码块的 this。(正因如此,call,apply,bind 就无法生效了,所以针对 this出现异常的情况,请优先考虑是否是因为箭头函数导致的。)

参考:https://blog.csdn.net/wswq2505655377/article/details/131962490

相关推荐

  1. vue使用lodash的debounce函数

    2024-03-23 15:02:03       60 阅读
  2. uniapp函数debounce使用

    2024-03-23 15:02:03       31 阅读
  3. vue 函数

    2024-03-23 15:02:03       46 阅读
  4. Vue箭头函数还原为匿名函数示例

    2024-03-23 15:02:03       47 阅读
  5. 箭头函数 this

    2024-03-23 15:02:03       27 阅读
  6. 箭头函数this指向问题

    2024-03-23 15:02:03       84 阅读

最近更新

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

    2024-03-23 15:02:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-23 15:02:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-23 15:02:03       82 阅读
  4. Python语言-面向对象

    2024-03-23 15:02:03       91 阅读

热门阅读

  1. 5 数据分析——matplotlib

    2024-03-23 15:02:03       36 阅读
  2. 【Qt5】QVariant

    2024-03-23 15:02:03       36 阅读
  3. 渔夫码头密语: 记录使用 Docker 安装 Wordpress

    2024-03-23 15:02:03       45 阅读
  4. ARP攻击是什么

    2024-03-23 15:02:03       45 阅读
  5. 蓝桥集训之格子游戏

    2024-03-23 15:02:03       38 阅读
  6. 基于FPGA实现的UDP协议栈设计_汇总

    2024-03-23 15:02:03       39 阅读
  7. 使用 `acme.sh` 申请 `Let‘s Encrypt` 证书部署服务器

    2024-03-23 15:02:03       41 阅读
  8. 哈工大sse C语言 困难

    2024-03-23 15:02:03       40 阅读
  9. 【华为OD机试】小明找位置【C卷|100分】

    2024-03-23 15:02:03       43 阅读
  10. 数据结构奇妙旅程之冒泡排序

    2024-03-23 15:02:03       38 阅读