公司项目用的ElementUI,其中用到了树组件,需求中有一个双击事件。然而官网只给了鼠标左键、右键的单击事件,需要在此基础上扩展一个双击事件,于是有了下面的写法:
<el-tree
:data="data"
node-key="id"
:props="defaultProps">
<span slot-scope="{node, data}">
<span @dblclick="clkDb()" @click="clk()">{{data.label}}</span>
</span>
</el-tree>
<script>
export default {
data() {
return {
data: []
}
},
methods: {
clk() {
console.log("click");
},
clkDb() {
console.log("db click");
}
}
}
</script>
尼玛!发现对同一元素添加单击@click和双击@dblclick事件时,双击事件执行之前单击事件总会执行两次,于是用函数去抖对此方法进行了修改:
<script>
let debounceTimer;
export default {
data() {
return {
data: [],
timer: null
}
},
methods: {
clk() {
debounceTimer = this.timer;
if (debounceTimer) {
window.clearTimeout(debounceTimer);
this.timer = null;
}
this.timer = window.setTimeout(() => {
console.log("click");
}, 300);
},
clkDb() {
debounceTimer = this.timer;
if (debounceTimer) {
window.clearTimeout(debounceTimer);
this.timer = null;
}
console.log("db click");
}
}
}
</script>