简单的判断是单击还是长按

604 阅读1分钟

判断是单击还是长按,其实就是对节流思想的运用

不懂节流和防抖的话,可以去了解一下。

直接上代码

样例

<template>
  <button @mousedown="onMousedown" @mouseup="onMouseup">点击或长按</button>
</template>

<script lang="ts">
import { ref } from "vue";
export default {
  setup() {
    let timeOutEvent = ref(0);
    function onMousedown(): void {
      timeOutEvent.value = setTimeout(() => {
        timeOutEvent.value = 0;
        console.log("长按");
      }, 600);
    }
    function onMouseup(): void {
      clearTimeout(timeOutEvent.value);
      if (timeOutEvent.value != 0) {
        //单击触发事件
        console.log("单击");
      }
    }
    return {
      onMousedown,
      onMouseup,
    };
  },
};
</script>

大功告成