lodash 防抖函数
2021-03-23 本文已影响0人
不忘初心_6b23
有这样一个需求,点击switch开关将状态值记录回后台。原始做法,添加事件并将调用后台接口。

然后连续点击开关看到接口请求情况如下 :

我们在连续点击的情况之下,会在每一次点击之后就会执行自定义函数的回调,这时如果你的回调中处理一些比较消耗内存的一些操作,或者调用接口之类,那么很有可能造成不必要的浪费以及阻塞,更可能会导致项目崩溃。
当当当,这个时候防抖函数就要上场了。
函数防抖: 频繁触发,但只在特定的时间内没有触发执行条件才执行一次代码
<template>
<el-switch
v-model="scope.row.status"
:active-value="1"
:inactive-value="0"
@change="val => changeStatus(val)"
active-color="#15A29E"
inactive-color="#D1D4DC"
>
</el-switch>
</template>
<script>
import { updateLabelStatus } from '@/api/dynamicLabel'
export default {
methods: {
//修改状态
changeStatus: _.debounce(function(item, val) {
updateLabelStatus(item.id, val).then(res => {
this.getTableList()
}).catch(() => {
this.getTableList()
})
}, 500),
}
}
</script>
酱紫,连续点击多次只执行一次。