节流/防抖

  • 1、节流:
    • 一个函数执行一行后,只有大于设定的执行周期后才会被执行第二次(点击事件)
    • 有个需要频繁触发的函数,出于优化性能角度,在规定时间内,只让函数触发的第一次生效后面不生效
    1. 防抖:
    • 一个需要频繁触发的函数,在规定时间内,只让最后一次生效,前面不生效

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

// 组件

const throttle = function (fn, wait = 50, isDebounce, ctx) {
let timer
let lastCall = 0
return function (...params) {
if (isDebounce) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(ctx, params)
}, wait);
} else {
const now = new Date().getTime()
if (now - lastCall < wait) return
lastCall = now
fn.apply(ctx, params)
}
}
}

export default {
name: "Throttle",
abstract: true,
props: {
time: Number,
events: String,
isDebounce: {
type: Boolean,
default: false
}
},
created() {
this.eventKeys = this.events.split(",")
this.originMap = {}
this.throttledMap = {}
},
render() {
const vnode = this.$slots.default[0]
this.eventKeys.forEach(key => {
const target = vnode.data.on[key]
if (target === this.originMap[key] && this.throttledMap[key]) {
vnode.data.on[key] = this.throttledMap[key]
} else if (target) {
this.originMap[key] = target
this.throttledMap[key] = throttle(target, this.time, this.isDebounce, vnode)
vnode.data.on[key] = this.throttledMap[key]
}
});
return vnode
}
}
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
// 通过第三个参数 isDebounce来控制切换防抖节流
// 在 main.js 引入
import Throttle from "./Throttle"
Vue.component("Throttle", Throttle)

// 使用
<div id="app">
<Throttle :timer="1000" events="click">
<botton @click="onClick($event, 1)">click + 1 {{val}}</botton>
</Throttle>
<Throttle :timer="1000" events="click" :isDebounce="true">
<botton @click="onAdd">click + 3 {{val}}</botton>
</Throttle>
<Throttle :timer="3300" events="mouseleave" :isDebounce="true">
<botton @mouseleave.prevent="onAdd">click + 3 {{val}}</botton>
</Throttle>
</div>

const app = new Vue({
el: "#app",
data() {
return {
val: 0
},
methods: {
onClick($ev,val) {
this.val = val
},
onAdd() {
this.val += 3
}
}
}
})
赞赏

本文地址: http://yoursite.com/2020/05/04/%E6%8A%BD%E8%B1%A1%E7%BB%84%E4%BB%B6/