vhook

useEvent


用于监听事件的 Hook

TIP

会在组件卸载时自动解绑事件,当 targetRef 时,target 变化时也会自动解绑事件

API

const [target, clear] = useEvent(event, cb, options, target = window)

Params

参数名描述类型默认值
event事件名string
cb事件监听回调Function
options传递给 addEventListenerremoveEventListener 的第三个参数bolean | AddEventListenerOptions
target绑定事件的目标EventTarget | Ref<EventTarget | null> | stringWindow

Result

参数说明类型
target事件绑定的目标对象interface IEventTarget {readonly value: EventTarget | null}
clear用于解绑事件() => void

Example

Code

<template>
  <div>
    <p>target 为 css 选择器</p>
    <button id="target">click</button>
  </div>
  <div>
    <p>target 为 Ref</p>
    <button ref="target">click</button>
  </div>
  <div>
    <p>target 为 DOM 对象</p>
    <button id="test">click</button>
  </div>
</template>
<script>
  import { ref, onMounted } from 'vue'
  import { useEvent } from 'vhook'
  export default {
    setup () {
      const target = ref(null)
      const handler = () => alert('click')
      useEvent('click', handler, true, '#target')
      useEvent('click', handler, true, target)
      onMounted(() => {
        useEvent('click', handler, true, document.getElementById('test'))
      })
      return {
        target
      }
    }
  }
</script>