vue2项目之防抖与节流的实现

防抖与节流(lodash.js)

我们这里用到一个第三方库:lodash.js

中文文档: https://www.lodashjs.com/docs/lodash.throttle

CDN:

<script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.corejs"></script>

vue里面安装及使用:

npm i lodash
import {
    
    debounce,throttle} from 'lodash'

methods: {
    
    
    addColor: throttle(function(index) {
    
    
        this.currentIndex = index;
    },50)
},

5.7.1 防抖

1、概念:前面的所有的触发都被取消,最后一次执行规定的时间 之后才会触发,也就是说如果连续快速的触发,只会执行最后一次

2、loadsh 中的 debounce 函数,参数为一个函数和防抖时间

3、一般用于表单的输入而触发的回调函数,实现当用户输入完成之后再执行回调函数

4、具体案例:当输入停止 且1s后 才会打印111

const input = document.querySelector('input');

input.oninput = _.debounce(function() {
    
    
    console.log('111');
},1000)

5.7.2 节流

1、概念:在规定的 间隔时间 内不会重复触发回调,只有大于这个时间间隔才会触发回调,把频繁触发变为少量触发

2、一般防止用户快速点击,例如1s内只能执行函数一次

3、loadsh 中的 throttle 函数,参数为一个函数和节流时间

4、使用(注意这里的 methods 函数使用方法)

import {
    
    throttle} from 'lodash'

methods: {
    
    
    addColor: throttle(function(index) {
    
    
        this.currentIndex = index;
    },50)
},

猜你喜欢

转载自blog.csdn.net/m0_63907100/article/details/129385816