# useEventListener

useEventListener

♻️ Register addEventListener (opens new window) on mounted, and removeEventListener (opens new window) automatically on unmounted.

# Example

💡 Example of MouseMove (opens new window) event. The following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an HTML5 canvas.

# Usage

<div class="wrapper">
  <h1>Drawing with mouse events</h1>
  <canvas id="myPics" width="560" height="360" class="border"></canvas>
</div>
1
2
3
4
import { useEventListener } from '@vueblocks/vue-use-core'

export default {
  setup () {
    const x = ref(0)
    const y = ref(0)
    const isDrawing = ref(false)
    
    onMounted(() => {
      const myPics = document.getElementById('myPics')
      const context = myPics.getContext('2d')

      const drawLine = (context, x1, y1, x2, y2) => {
        context.beginPath()
        context.strokeStyle = 'black'
        context.lineWidth = 1
        context.moveTo(x1, y1)
        context.lineTo(x2, y2)
        context.stroke()
        context.closePath()
      }

      const onMouseDown = e => {
        x.value = e.offsetX
        y.value = e.offsetY
        isDrawing.value = true
      }

      const onMouseMove = e => {
        if (isDrawing.value === true) {
          drawLine(context, x.value, y.value, e.offsetX, e.offsetY)
          x.value = e.offsetX
          y.value = e.offsetY
        }
      }

      const onMouseUp = e => {
        if (isDrawing.value === true) {
          drawLine(context, x.value, y.value, e.offsetX, e.offsetY);
          x.value = 0
          y.value = 0
          isDrawing.value = false
        }
      }

      useEventListener(myPics, 'mousedown', onMouseDown)
      useEventListener(myPics, 'mousemove', onMouseMove)
      useEventListener(window, 'mouseup', onMouseUp)
    })
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

# Typing

declare function useEventListener<E extends keyof WindowEventMap>(target: Window, event: E, listener: (this: Window, ev: WindowEventMap[E]) => any, options?: boolean | AddEventListenerOptions): Fn;
declare function useEventListener<E extends keyof DocumentEventMap>(target: Document, event: E, listener: (this: Document, ev: DocumentEventMap[E]) => any, options?: boolean | AddEventListenerOptions): Fn;
declare function useEventListener<E extends keyof DocumentEventMap>(target: RefElement | Ref<any>, event: E, listener: (this: Element, ev: DocumentEventMap[E]) => any, options?: boolean | AddEventListenerOptions): Fn;
declare function useEventListener(target: MaybeRef<EventTarget>, event: string, listener: EventListener, options?: boolean | AddEventListenerOptions): Fn;
1
2
3
4