当前位置: 首页 > news >正文

vue中使用lodash的debounce(防抖函数)

1、安装

npm i --save lodash.debounce

2、引入

import debounce from 'lodash.debounce'

3、使用

<van-search v-model="searchValue" placeholder="输入姓名或工号" @input='handleInput' />

第一种:

handleInput: debounce(function (val) {console.log(val)
}, 200)

第二种:

handleInput(val) {console.log(val)
}
created() {this.handleInput = debounce(this.handleInput, 200) // 搜索框防抖
}

这两种使用方式效果一样

观察者防抖:

<template><input v-model="value" type="text" /><p>{{ value }}</p>
</template>
<script>
import debounce from "lodash.debounce";
export default {data() {return {value: "",};},watch: {value(...args) {this.debouncedWatch(...args);},},created() {this.debouncedWatch = debounce((newValue, oldValue) => {console.log('New value:', newValue);}, 500);},beforeUnmount() {this.debouncedWatch.cancel();},
};
</script>

事件处理器防抖:

<template><input v-on:input="debouncedHandler" type="text" />
</template>
<script>
import debounce from "lodash.debounce";
export default {created() {this.debouncedHandler = debounce(event => {console.log('New value:', event.target.value);}, 500);},beforeUnmount() {this.debouncedHandler.cancel();}
};
</script>

为什么不在method中写好方法,在template中直接调用,就像这样

<template><input v-on:input="debouncedHandler" type="text" />
</template>
<script>
import debounce from "lodash.debounce";
export default {methods: {// Don't do this!debouncedHandler: debounce(function(event) {console.log('New value:', event.target.value);}, 500)}
};
</script>

组件使用 export default { … } 导出的 options 对象,包括方法,会被组件实例重用。

如果网页中有 2 个以上的组件实例,那么所有的组件都会应用 相同 的防抖函数 methods.debouncedHandler — 这会导致防抖出现故障。

http://www.lryc.cn/news/536717.html

相关文章:

  • 什么是耐环境环形光源
  • 3dtiles——Cesium ion for Autodesk Revit Add-In插件
  • Edge浏览器清理主页
  • leetcode刷题第十天——栈与队列Ⅱ
  • 硬修复(hPPR)与软修复(sPPR)
  • filebeat抓取nginx日志
  • TLQ-CN10.0.2.0 (TongLINK/Q-CN 集群)部署指引 (by lqw)
  • 第 14 天:UE5 C++ 与蓝图(Blueprint)交互!
  • 小初高各学科教材,PDF电子版下载
  • Trader Joe‘s EDI 需求分析
  • python class详解
  • 基于LVS负载均衡练习
  • 在 rtthread中,rt_list_entry (rt_container_of) 已知结构体成员的地址,反推出结构体的首地址
  • 数组_二分查找
  • VUE环境搭建
  • MATLAB图像处理:Sobel、Roberts、Canny等边缘检测算子
  • C++ 标准库常见容器
  • Ubuntu+Laravel+MQ+Supervisor队列系统搭建流程
  • 力扣100. 相同的树(利用分解思想解决)
  • 全面了解HTTP(一)
  • element-ui时间组件同一个月内选择/30天内选择
  • NO.18十六届蓝桥杯备战|循环嵌套|乘法表|斐波那契|质数|水仙花数|(C++)
  • 深入浅出Java反射:掌握动态编程的艺术
  • 大模型被偷家?CNN结合多模态!
  • UI自动化测试的优缺点?
  • 在 Kubernetes (K8s) 环境中,备份 PostgreSQL 数据库
  • 机器视觉中的3d和2d的区别
  • exr 格式下 全景图(经纬图、panorama)转 cubemap
  • STM32 ADC介绍(硬件原理篇)
  • snort3.0 获取注册规则(19000多条)