useEventListener

useEventListener 用于封装原生的 addEventListener 方法,使得在函数式组件中添加事件监听器更加方便

基础用法

<template>
  <div>
    <p>You clicked the button {{ count }} times</p>
    <button ref="buttonRef">Click me</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useEventListener } from "hooks-vue3";
const count = ref(0);
const buttonRef = ref(null);

function handleClick() {
  count.value++;
}

// Add event listener using our hook
useEventListener("click", handleClick, {
  target: buttonRef,
});

</script>

API

useEventListener("click", ()=>void, {
  target,
});

参数


type Target<T> = T | (() => T) | Ref<T> | Window | Document;

type Options = {
  target?: Target<Element | null>;
  capture?: boolean;
  passive?: boolean;
};

function useEventListener(
  type: string,
  listener: EventListener,
  options?: Options,
): (() => void) 

Last updated