vue为同一个元素绑定单击和双击事件,不相互影响执行各自的逻辑

vue为同一个元素绑定单击和双击事件,不相互影响执行各自的逻辑

在Vue中,由于双击事件 dblclick 会先触发两次单击事件 click,无法直接通过简单的处理逻辑来解决。要实现这个需求,可以借助一些额外的技巧,例如使用 setTimeout 来延迟判断是否触发单击事件。

<template>
  <div>
    <button @click="handleClick" @dblclick="handleDoubleClick">Click me</button>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      clickCount: 0,
      clickTimer: null
    };
  },
  methods: {
    
    
    handleClick() {
    
    
      this.clickCount++;
      if (this.clickCount === 1) {
    
    
        this.clickTimer = setTimeout(() => {
    
    
          // 单击事件处理逻辑
          console.log('Click event');
          this.clickCount = 0;
        }, 200);
      }
    },
    handleDoubleClick() {
    
    
      clearTimeout(this.clickTimer);
      this.clickCount = 0;
      // 双击事件处理逻辑
      console.log('Double click event');
    }
  }
}
</script>

在上述示例中,我们使用了 clickCount 变量来跟踪单击事件的次数,以及 clickTimer 变量来存储 setTimeout 的返回值。在单击事件处理函数中,我们根据点击次数来决定是否延迟触发单击事件。当点击次数为1时,启动一个定时器,在延迟时间内判断是否触发单击事件。如果在延迟时间内双击事件被触发,我们清除定时器,并将点击次数重置为0。而在双击事件处理函数中,我们清除定时器,并将点击次数重置为0,然后执行双击事件的逻辑。

通过这种方式,我们可以实现在Vue中给同一个元素绑定单击事件和双击事件,并确保双击事件不会触发单击事件。

猜你喜欢

转载自blog.csdn.net/m0_46672781/article/details/131450550