Browser · @vueuse/core v15.0.0 · Reviewed

useEventListener

Attach a browser event listener and let VueUse remove it when the owning component is disposed.

App.vueVue SFCOpen in Vue Playground ↗
Live preview

Edit the code and the preview updates as you type.

What it does

A page-level keyboard shortcut needs a window listener, but forgetting cleanup can leave duplicate handlers after navigation.

The playground is a small, runnable example. Change the code and try the interaction before copying it into an app.

The code

Vue · Composition API
useEventListener(window, 'keydown', (event) => {
  if (event.key === 'Escape') closePanel()
})

Where you'd use it

  • Escape shortcuts for a panel
  • A resize listener for a canvas
  • Listening to a target that changes with a template ref

In Nuxt (and other gotchas)

Do not evaluate window at module scope or during server rendering. Register the listener from setup after the component is created, or pass a template ref as the target when the element is rendered conditionally.

When not to use it

Use a normal element event binding for events on an element in your template. A global listener is appropriate only when the event target is genuinely global.

Links

Need a hand with your Vue or Nuxt app?

Related functions