Debounce组件:
<script>
import { get, debounce, set } from 'lodash';
export default {
name: 'debounce',
abstract: true, //标记为抽象组件
props: {
events: String,
wait: {
type: Number,
default: 0,
},
options: {
type: Object,
default() {
return {};
},
},
},
render() {
let vnode = this.$slots.default[0]; // 子组件的vnode
if (vnode && this.events) {
let eventList = this.events.split(',');
eventList.forEach(eventName => {
let event = get(vnode, `data.on[${eventName}]`); // 子组件绑定的click事件
if (typeof event === 'function') {
set(vnode, `data.on[${eventName}]`, debounce(event, this.wait, this.options));
}
if (!event) {
event = get(vnode, `componentOptions.listeners[${eventName}]`);
if (typeof event === 'function') {
set(vnode, `componentOptions.listeners[${eventName}]`, debounce(event, this.wait, this.options));
}
}
});
}
return vnode;
},
};
</script>
使用:
<debounce events="click" :wait="250" :options="{ maxWait: 1000 }">
<button @click="click">点击</button>
</debounce>
<debounce events="click" :wait="250" :options="{ maxWait: 1000 }">
<el-button @click="click">点击</el-button>
</debounce>