Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k 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 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...