vue中使用loadsh的debounce防抖函数问题
使用loadsh的debounce防抖函数
<s-input placeholder="请输入查询关键字" prefix-icon="magnifier" v-model="content"></s-input>
<script>
import {debounce} from 'lodash'
export default {
watch: {
content: debounce(function(newVal, oldVal) {
this.search()
}, 1000)
},
methods:{
search(){
$axios.post('').then((res) => {})
}
}
}
</script>
<s-button @click="handleSave"></s-button>
<script>
import {debounce} from 'lodash'
export default {
methods:{
handleSave: debounce(function() {
//执行方法
},1000),
}
}
</script>
debounce防抖函数的使用(js和vue)
debounch防抖函数主要应用场景,解决按钮快速点击,多次请求的问题和input输入框多次请求的问题。接下来直接介绍在js和vue项目中的使用方式。
lodash工具库地址:https://lodash.com/docs#debounce
三个参数:
_.debounce(func, [wait=0], [options={}])options 有如下三个可选参数配置:
leading:指定在延迟开始前是否执行 func(默认为 false)。maxWait:设置 func 允许被延迟的最大值。trailing:指定在延迟结束后是否执行 func(默认为 true)
1.在js项目中的使用
(1)引用lodash工具库:
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
(2)代码:html:<div class="ceshi">点击测试</div>
js:使用jq需引入jq库,否则报错
$(".ceshi").on("click",function(){
showAlert()
})
let showAlert = _.debounce(ceshiFun,400,
{'leading': true,
'trailing': false})
function ceshiFun(){
console.log("测试")
}2.在vue项目中的使用
(1)安装。进入项目文件夹,执行如下命令使用 npm 安装 lodash:npm i --save lodash
(2)引入项目:import _ from 'lodash'
(3)在项目中使用示例:
<template>
<div id="test">
<button @click="btnClick">点击</button>
</div>
</template>
<script>
import _ from 'lodash';
export default {
name: 'Test',
data () {
return {
}
},
methods:{
//按钮点击
btnClick() {
//显示消息
this.showAlert('欢迎访问hangge.com');
},
// 显示消息时增加防抖(500毫秒延迟)
showAlert: _.debounce(function(message){
alert(message);
}, 500)
},
// 页面创建时自动加载数据
created() {
}
}
</script>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
详解vue2.0+vue-video-player实现hls播放全过程
这篇文章主要介绍了详解vue2.0+vue-video-player实现hls播放全过程,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-03-03
vue中v-for和v-if一起使用之使用compute的示例代码
这篇文章主要介绍了vue中v-for和v-if一起使用之使用compute的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-05-05
解决Vue警告Write operation failed:computed value is readonl
这篇文章主要给大家介绍了关于如何解决Vue警告Write operation failed:computed value is readonly的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下2023-03-03
vue项目前端微信JSAPI与外部H5支付相关实现过程及常见问题
这篇文章主要介绍了vue项目前端微信JSAPI与外部H5支付相关实现过程及常见问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-04-04


最新评论