# 复用代码
# 防抖节流
需求,一个数字需要根据输入内容计算得到,需要防抖,代码实现
// utils/debounce.js
// 防抖
export function _debounce(fn, delay) {
var delay = delay || 200;
var timer;
return function () {
var th = this;
var args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
timer = null;
fn.apply(th, args);
}, delay);
};
}
// 节流
export function _throttle(fn, interval) {
var last;
var timer;
var interval = interval || 200;
return function () {
var th = this;
var args = arguments;
var now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(function () {
last = now;
fn.apply(th, args);
}, interval);
} else {
last = now;
fn.apply(th, args);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<template>
<div>
<van-field v-model="a" label="xx" placeholder="请输入xxx" @input="handleInputPSClick($event, b,c)" />
</div>
</template>
<script>
import { _debounce } from "../../utils/debounce";
export default {
name: "",
data() { return {}; },
methods: {
// 写法: ------------------------------
handleInputPSClick: _debounce(function (value, b, c) {
// 数据处理 ...
// 1. value是方法中input的值
// 2. b c 是传过来的参数
}, 500),
// 写法: ------------------------------
handleInputPSClick: _debounce(this.fn, 500),
fn(){console.log("测试")}
};}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 查看页面中的哪个盒子产生的滚动
在console面板中,输入以下代码,滚动滚动条就可以看见了
function findscroller(element) {
element.onscroll = function () {
console.log(element)
}
Array.from(element.children).forEach(findscroller)
}
findscroller(document.body)
1
2
3
4
5
6
7
2
3
4
5
6
7