Skip to content

useCustomInputValue

方便地进行事件绑定,在组件 mountedactivated 时绑定事件,unmounteddeactivated 时解绑事件。

基本用法

js
import { ref } from 'vue'
import { useEventListener } from '@ryxon/use'

export default {
  setup() {
    // 在 window 上绑定 resize 事件
    // 未指定监听对象时,默认会监听 window 的事件
    useEventListener('resize', () => {
      console.log('window resize')
    })

    // 在 body 元素上绑定 click 事件
    useEventListener(
      'click',
      () => {
        console.log('click body')
      },
      { target: document.body }
    )
  }
}

取消事件监听

useEventListener 会返回一个 cleanup 函数,调用该函数可以取消事件监听。

js
import { ref } from 'vue'
import { useEventListener } from '@ryxon/use'

export default {
  setup() {
    const cleanup = useEventListener('resize', () => {
      console.log('window resize')
    })

    cleanup()
  }
}

API

类型定义

ts
type Options = {
  target?: EventTarget | Ref<EventTarget>
  capture?: boolean
  passive?: boolean
}

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

参数

参数说明类型默认值
type监听的事件类型string-
listener事件回调函数EventListener-
options可选的配置项Options-

Options

参数说明类型默认值
target绑定事件的元素EventTarget | Ref\<EventTarget>window
capture是否在事件捕获阶段触发booleanfalse
passive设置为 true 时,表示 listener 永远不会调用 preventDefaultbooleanfalse

Released under the MIT License.