节流与防抖在vue中的应用

这是今天面试时被点拨的一点,自定义指令封装节流防抖函数

非自定义指令版节流

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
// debounce.js
export const debounce = function (fn, delay) {
let timer = null
let immediate = true
return function () {
const _this = this
if (immediate) {
fn.apply(_this)
immediate = false
} else {
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(_this)
}, delay);
}

}
}

// 某个.vue文件
import { debounce } from '../utils/debounce'

methods: {
test: debounce(function () {
this.count++
}, 1000),
}

自定义指令节流

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
// debounce.js
import Vue from 'vue'

Vue.directive('debounce', {
inserted(el, binding) {
let {
fn,
event = "click",
delay = 800
} = binding.value;
let timer = null;
let immediate = true
el.addEventListener(event, function () {
if (immediate) {
fn()
immediate = false
} else {
clearTimeout(timer)
timer = setTimeout(function () {
fn()
}, delay)
}

})
}
})

// main.js
import "@/directive/debounce"

// 某个.vue文件
<button v-debounce="{ fn: test, delay: 1000 }">click</button>

非自定义指令版防抖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// throttle.js
export const throttle = function (fn, delay) {
let timer = null;
return function () {
const _this = this
if (!timer) {
timer = setTimeout(function () {
fn.apply(_this)
timer = null;
}, delay);
}
}
}

// 用法同上

自定义指令版防抖

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
import Vue from 'vue'

Vue.directive('throttle', {
inserted(el, binding) {
let {
fn,
event = "click",
delay = 800
} = binding.value;
let timerB = null;
let flag = true
el.addEventListener(event, () => {
if (flag) {
flag = false
fn.apply(this, arguments);
timerB = setTimeout(() => {
flag = true
clearTimeout(timerB);
timerB = null
}, delay);
}
});
},
});


节流与防抖在vue中的应用
https://xypecho.github.io/2023/08/08/节流与防抖在vue中的应用/
作者
很青的青蛙
发布于
2023年8月8日
许可协议