Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

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>

像这样写似乎无法触发


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...