uniapp项目使用防抖及节流的方案实战
2023-01-19 12:37:13 来源:易采站长站 作者:
目录此方案出现的理由实现方案及效果总结此方案出现的理由小程序中无法使用vue.directive的指令方法函数实现防抖节流传统的防抖节流方式相对繁琐实现方案及效果新建一个debounce-view组件...
目录
此方案出现的理由实现方案及效果
总结
此方案出现的理由
小程序中无法使用vue.directive的指令方法函数实现防抖节流传统的防抖节流方式相对繁琐
实现方案及效果
新建一个debounce-view组件直接用debounce-view包裹需要防抖的内容即可,如下:
<debounce-view @thtap="buyNow"> <view class="buy-now">立即购买</view> </debounce-view>
防抖组件内容:
//debounce-view <template> <view @click.stop="deTap"> <slot></slot> </view> </template> <script> function deBounce(fn, delay = 500, immediate) { let timer = null, immediateTimer = null; return function() { let args = arguments, context = this; // 第一次触发 if (immediate && !immediateTimer) { fn.apply(context, args); //重置首次触发标识,否则下个周期执行时会受干扰 immediateTimer = setTimeout(() => { immediateTimer = null; }, delay); } // 存在多次执行时,重置动作需放在timer中执行; if (immediateTimer) clearTimeout(immediateTimer); if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(context, args); timer = null; immediateTimer = null; }, delay); } } export default { methods: { deTap: deBounce(function() { console.log('deTap') this.$emit('deTap') }, 500, true), } } </script> <style> </style>
节流组件内容:
<template> <view @click.stop="thTap"> <slot></slot> </view> </template> <script> // 第二版 function throttle(func, wait) { var timeout; var previous = 0; return function() { context = this; args = arguments; if (!timeout) { timeout = setTimeout(function() { timeout = null; func.apply(context, args) }, wait) } } } export default { methods: { thTap: throttle(function() { this.$emit('thTap') }, 500) } } </script> <style> </style>
总结
上述方法有有点但也有缺点,优点是使用起来非常的快捷方便,缺点是时间目前是写死的,各位看官如果有新的想法或者意见还请指教小弟一二到此这篇关于uniapp项目使用防抖及节流的文章就介绍到这了,更多相关uniapp使用防抖及节流内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
如有侵权,请发邮件到 [email protected]
最新图文推荐
相关文章
-
Vue+elementUI实现多图片上传与回显功能(含回显后继续上传或删除
最近有使用vue+elementUI实现多图片上传的需求,遂做此纪录。 本次主要写一下前端的实现细节,至于后台以Multipart[ ]数组接收即可,不再赘述,网上一搜大把文章可供参考。 本次使用2020-03-23
-
Vue-router 报错NavigationDuplicated的解决方法
版本:3.1.x 报错原因: 使用push()、replace()进行导航时,不能重复导航到当前路由。 解决办法: 方法1:在定义路由的文件中router/index.js const originalPush = VueRouter.prototype.pushVueRouter.protot2020-03-31