vue3 compositionApi如何实现click事件节流?

<MButton @click="output">button</MButton>
...
<template>
  <button @click="handleClick">
    <slot></slot>
  </button>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, watch, computed } from 'vue'

export default defineComponent({
  name: 'MButton',
  emits: {
    click: null
  },
  setup(props, { attrs, emit }) {

    const throttle = (fn: string, delay: number = 500) => {
      let timer: number = null
      return (...args: []) => {
        if (!timer) {
          emit(fn, args)
          timer = window.setTimeout(() => {
            timer = null
          }, delay)
        }
      }
    }

    function handleClick() {
      // emit('click')
      throttle('click', 500)
    }

    return {
      handleClick,
    }
  },
})
</script>

像这样写似乎无法触发

阅读 4.6k
2 个回答

@click 这个绑定的应该是你throttle处理后的函数。用法和vue2一样的,你写法中的误区是每次执行都调用了throttle。

vueuse这个库有相关实现

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题