需求:搜索按钮增加防抖功能
代码1
<template>
<el-button type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
</template>
<script>
import { debounce } from "lodash";
// 自定义搜索按钮,带防抖
export default {
name: "SearchButton",
props: {
//默认等待1秒
wait: {
type: Number,
default: 1000
}
},
components: {},
data () {
return {
};
},
mounted () {
//防抖函数
this.debounceClick=debounce(function(){
console.log(111111);
},this.wait)
},
methods: {
/**
* 点击事件
*/
searchClick () {
this.debounceClick()
}
//或是
searchClick :debounce(function(){
console.log(111111);
},this.wait)
}
};
</script>
参考:
https://vuejs.org/guide/essentials/reactivity-fundamentals.html#stateful-methods
注:debounce返回的是一个函数,debounce后面增加()或直接在点击事件中调用是不行的
searchClick () {
//不执行
debounce(function(){
console.log(111111);
},this.wait)
}
searchClick () {
//每次都执行
debounce(function(){
console.log(111111);
},this.wait)()
}