场景
业务需要,要求ElementUI的Tree组件同时拥有单击和双击两种事件。官方组件API只提供了单击事件,双击事件则需要自己扩展。(扩展不是本篇的重点)
问题
扩展好双击事件,代码如下:
<template>
<div>
<el-tree :data="data" node-key="id" :props="defaultProps">
<span slot-scope="{ node, data }">
<span @nodedbclick="nodeDbClick" @click="nodeClik">{{
data.label
}}</span></span
>
</el-tree>
</div>
</template>
<script>
export default {
data() {
return {
data: []
};
},
methods: {
nodeClik() {
console.log("触发单击");
},
nodeDbClick() {
console.log("触发双击");
}
}
};
</script>
在触发双击事件之前,总会触发两次单击事件,显然会影响具体的业务操作!
解决
使用防抖解决此问题!!!!
<script>
let debounceTimer;
export default {
data() {
return {
data: [],
timer: null,
};
},
methods: {
nodeClik() {
debounceTimer = this.timer;
if (debounceTimer) {
window.clearTimeout(debounceTimer);
this.timer = null;
}
this.timer = window.setTimeout(() => {
console.log("触发单击");
}, 500);
},
nodeDbClick() {
debounceTimer = this.timer;
if (debounceTimer) {
window.clearTimeout(debounceTimer);
this.timer = null;
}
console.log("触发双击");
}
}
};
</script>