Diretório de artigos
Antivibração + código de limitação
- O código não é um problema
scr/utils/utils.js
// 防抖函数| f 要执行的函数 | deley 延时(毫秒),默认100 | firstRun 第一次是否执行 true就是执行,默认false, // // // // // // // // // // // // //
function debounce(f, deley = 100, firstRun = false) {
let time666
// 第一次是否执行
if (firstRun === true) f();
return (_, ...args) => {
clearTimeout(time666)
time666 = setTimeout(__ => f.apply(_, args), deley)
}
};
// 节流 f-函数 deley-延时
function throttle(f, deley = 500) {
let time = null;
return (_, ...args) => {
if (time !== null) return
time = setTimeout(() => {
f.apply(_, args)
time = null
}, deley);
}
}
export {
debounce,
throttle
}
demanda + limitação de chamadas
precisar
- Quando o botão é clicado com frequência, ele será executado uma vez a cada 1200 milissegundos
chamada errada
<template>
<button @click="florCard.florClk1">调用1</button>
<button @click="throttle(lorCard.florClk2,1200)">调用2</button>
<button @click="throttle(lorCard.florClk3,1200)">调用3</button>
</template>
<script setup>
import {
throttle } from '@/utils/utils'
const florCard = {
//错误 1
florClk1() {
throttle(() => console.log(1), 1200)
},
//错误 2
florClk2: function() {
console.log(1);
},
// 错误 3
florClk3() {
console.log(1);
},
}
</script>
ligue corretamente
Uma variável deve ser definida para receber a função de retorno anti-vibração/estrangulamento, conforme a seguirfn
src/views/homeView.vue
<template>
<button @click="b(1, 2, 3)">按钮1111</button>
</template>
<script setup>
/**
* 定义一个变量存储防抖函数的返回值
* 注:防抖函数返回的是一个函数,所以,fn存储的是个函数
*/
let fn = null
const a = _ => console.log(_)
const b = (...args) => {
/**
* 注:想要达到防抖与节流,最终调用的是防抖火或节流函数返回的函数
* 若第一次调用b函数,且fn为null,则先调用防抖函数
* 并使用fn变量存储防抖函数返回的函数
* 也就是说真正调用的是fn函数,而非debounce
*/
if (!fn) {
fn = debounce(a)
}
fn(args)
}
const debounce = (fn, deley = 400) => {
let time = null
return (...args) => {
clearTimeout(time)
time = setTimeout(_=> fn.apply(null, args), deley)
}
}
</script>
ponto importante
Pontos de atenção antivibração + estrangulamento |
---|
Quando anti-shake/throttling é usado em eventos vue,需调用防抖/节流返回的函数 。并非直接调用debounce、throttle 函数 |
O princípio de throttling + anti-shake é retornar uma função e chamar a função retornada para obter o efeito de anti-shake + throttling |
- O método de chamada errado acima,
- Porque uma função normal é chamada, e então o anti-shake/throttle é chamado. Neste momento, o anti-shake/throttle retorna uma função, mas a função retornada pelo anti-shake/throttle não é chamada, e o anti -o efeito de vibração/acelerador não é alcançado.
- Adicione parênteses após as funções antivibração e limitação para chamar as funções antivibração e limitação. No entanto, toda vez que o botão for clicado , o antivibração e o estrangulamento serão acionados continuamente , e o efeito do antivibração e do estrangulamento não será alcançado no final.
Fim
Série 2023/03/12
2023/03/15 Revisado
21/04/2023 19:55 2 Modificado