matijao/webdev huggingface dataset:
useWebWorker | VueUse

useWebWorker
​
Category
Browser
Export Size
322 B
Last Changed
6 months ago
Related
useWebWorkerFn

Simple Web Workers registration and communication.

Usage
​
js
import { useWebWorker } from '@vueuse/core'

const { data, post, terminate, worker } = useWebWorker('/path/to/worker.js')
State	Type	Description
data	Ref<any>	Reference to the latest data received via the worker, can be watched to respond to incoming messages
worker	ShallowRef<Worker | undefined>	Reference to the instance of the WebWorker
Method	Signature	Description
post	(message: any, transfer: Transferable[]): void
`(message: any, options?: StructuredSerializeOptions	undefined): void`
terminate	() => void	Stops and terminates the worker.
Source
​

Source • Docs

Contributors
​
Anthony Fu
Antério Vieira
Yasser Lahbibi
DarknessChaser
Young
karma
Shinigami
Mario Kolli
Shinigami
wheat
Alex Kozack
userquin
Changelog
​
v10.2.0 on 6/16/2023
5988f - fix: add web worker transferable option (#3123)
v10.0.0-beta.5 on 4/13/2023
cb644 - refactor!: remove isFunction and isString utils
v9.4.0 on 10/25/2022
c8849 - feat: support overloads (#2259)
useWebWorkerFn | VueUse

useWebWorkerFn
​
Category
Browser
Export Size
749 B
Last Changed
2 months ago
Related
useWebWorker

Run expensive functions without blocking the UI, using a simple syntax that makes use of Promise. A port of alewin/useWorker.

Demo
​

source

Current Time: 2023-11-28 22:16:47 888

This is a demo showing sort for large array (5 million numbers) with or w/o WebWorker.
Clock stops when UI blocking happens.
Sort in Main ThreadSort in Worker
Usage
​
Basic example
​
js
import { useWebWorkerFn } from '@vueuse/core'

const { workerFn } = useWebWorkerFn(() => {
  // some heavy works to do in web worker
})
With dependencies
​
ts
import { useWebWorkerFn } from '@vueuse/core'

const { workerFn, workerStatus, workerTerminate } = useWebWorkerFn(
  dates => dates.sort(dateFns.compareAsc),
  {
    timeout: 50000,
    dependencies: [
      'https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js', // dateFns
    ],
  },
)
Web Worker
​

Before you start using this function, we suggest you read the Web Worker documentation.

Credit
​

This function is a Vue port of https://github.com/alewin/useWorker by Alessio Koci, with the help of @Donskelle to migration.

Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Fabian
wheat
sibbng
Antério Vieira
Luvoy
Hawtim
烽宁
Jelf
不见月
Shinigami
Alex Kozack
Richard Musiol
Changelog
​
v10.4.0 on 8/25/2023
34206 - fix(useWebWorker): prevent error event bubbling (#3141)
v8.9.3 on 7/14/2022
52467 - fix!: rename type WebWorkerOptions to UseWebWorkerOptions (#1896)
useWebNotification | VueUse

useWebNotification
​
Category
Browser
Export Size
964 B
Last Changed
2 months ago

Reactive Notification

The Web Notification interface of the Notifications API is used to configure and display desktop notifications to the user.

Demo
​

source

Supported: true

Show Notification
Usage
​
ts
const {
  isSupported,
  notification,
  show,
  close,
  onClick,
  onShow,
  onError,
  onClose,
} = useWebNotification({
  title: 'Hello, VueUse world!',
  dir: 'auto',
  lang: 'en',
  renotify: true,
  tag: 'test',
})

if (isSupported.value)
  show()

This composable also utilizes the createEventHook utility from '@vueuse/shared`:

TypeScript
ts
onClick((evt: Event) => {
  // Do something with the notification on:click event...
})
onShow((evt: Event) => {
  // Do something with the notification on:show event...
})
onError((evt: Event) => {
  // Do something with the notification on:error event...
})
onClose((evt: Event) => {
  // Do something with the notification on:close event...
})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
Sampson Crowley
Michael J. Roberts
丶远方
WuLianN
donotloveshampo
Michael J. Roberts
Changelog
​
v10.5.0 on 10/7/2023
2f2b4 - fix: condition check on permission (#3422)
v10.4.0 on 8/25/2023
a1753 - feat: add requestPermissions option, return permissionGranted and ensurePermissions (#3325)
v10.0.0-beta.0 on 3/14/2023
bcd2a - fix!: should be exposed as EventHooksOn (#2821)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
useWakeLock | VueUse

useWakeLock
​
Category
Browser
Export Size
727 B
Last Changed
8 months ago

Reactive Screen Wake Lock API. Provides a way to prevent devices from dimming or locking the screen when an application needs to keep running.

Demo
​

source

Is Supported: true
Is Active: false
ON
Usage
​
js
import { useWakeLock } from '@vueuse/core'

const { isSupported, isActive, request, release } = useWakeLock()

If request is called, isActive will be true, and if release is called, or other tab is displayed, or the window is minimized,isActive will be false.

Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
vuff
HannesOberreiter
wheat
koheing
Changelog
​
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
useVibrate | VueUse

useVibrate
​
Category
Browser
Export Size
671 B
Last Changed
8 months ago

Reactive Vibration API

Most modern mobile devices include vibration hardware, which lets software code provides physical feedback to the user by causing the device to shake.

The Vibration API offers Web apps the ability to access this hardware, if it exists, and does nothing if the device doesn't support it.

Usage
​

Vibration is described as a pattern of on-off pulses, which may be of varying lengths.

The pattern may consist of either a single integer describing the number of milliseconds to vibrate, or an array of integers describing a pattern of vibrations and pauses.

ts
import { useVibrate } from '@vueuse/core'

// This vibrates the device for 300 ms
// then pauses for 100 ms before vibrating the device again for another 300 ms:
const { vibrate, stop, isSupported } = useVibrate({ pattern: [300, 100, 300] })

// Start the vibration, it will automatically stop when the pattern is complete:
vibrate()

// But if you want to stop it, you can:
stop()
Source
​

Source • Docs

Contributors
​
Anthony Fu
Jelf
Mangokk
Michael J. Roberts
Changelog
​
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useTitle | VueUse

useTitle
​
Category
Browser
Export Size
903 B
Last Changed
8 months ago

Reactive document title.

TIP

When using with Nuxt 3, this function will NOT be auto imported in favor of Nuxt's built-in useTitle(). Use explicit import if you want to use the function from VueUse.

Demo
​

source

Title
Usage
​
js
import { useTitle } from '@vueuse/core'

const title = useTitle()
console.log(title.value) // print current title
title.value = 'Hello' // change current title

Set initial title immediately:

js
const title = useTitle('New Title')

Pass a ref and the title will be updated when the source ref changes:

js
import { useTitle } from '@vueuse/core'

const messages = ref(0)

const title = computed(() => {
  return !messages.value ? 'No message' : `${messages.value} new messages`
})

useTitle(title) // document title will match with the ref "title"

Pass an optional template tag Vue Meta Title Template to update the title to be injected into this template:

js
const title = useTitle('New Title', { titleTemplate: '%s | My Awesome Website' })

WARNING

observe is incompatible with titleTemplate.

Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Alex Kozack
Antério Vieira
ClemDee
Eugen Istoc
Levi (Nguyễn Lương Huy)
Preetesh Jain
Michael Roberts
Changelog
​
v10.0.0-beta.5 on 4/13/2023
cb644 - refactor!: remove isFunction and isString utils
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef
v9.3.1 on 10/17/2022
8c1ba - fix: prevent observe and titleTemplate been specified at the same time (#2049)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useTextDirection | VueUse

useTextDirection
​
Category
Browser
Export Size
821 B
Last Changed
last year

Reactive dir of the element's text.

Demo
​

source

This paragraph is in English and correctly goes left to right.

LTRClick to change the direction
Usage
​
ts
import { useTextDirection } from '@vueuse/core'

const dir = useTextDirection() // Ref<'ltr' | 'rtl' | 'auto'>

By default, it returns rlt direction when dir rtl is applied to the html tag, for example:

html
<!--ltr-->
<html> ... </html>

<!--rtl-->
<html dir="rtl"> ... </html>
Options
​
ts
import { useTextDirection } from '@vueuse/core'

const mode = useTextDirection({
  selector: 'body'
}) // Ref<'ltr' | 'rtl' | 'auto'>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
iChengbo
Nestor Vera
Changelog
​
v9.0.0-beta.2 on 7/24/2022
085be - feat: new function (#1678)
useStyleTag | VueUse

useStyleTag
​
Category
Browser
Export Size
474 B
Last Changed
3 weeks ago

Inject reactive style element in head.

Demo
​

source

Edit CSS:
LoadUnload

ID: vueuse_styletag_1

Loaded: true

Usage
​
Basic usage
​

Provide a CSS string, then useStyleTag will automatically generate an id and inject it in <head>.

js
import { useStyleTag } from '@vueuse/core'

const {
  id,
  css,
  load,
  unload,
  isLoaded,
} = useStyleTag('.foo { margin-top: 32px; }')

// Later you can modify styles
css.value = '.foo { margin-top: 64px; }'

This code will be injected to <head>:

html
<style id="vueuse_styletag_1">
.foo { margin-top: 64px; }
</style>
Custom ID
​

If you need to define your own id, you can pass id as first argument.

js
import { useStyleTag } from '@vueuse/core'

useStyleTag('.foo { margin-top: 32px; }', { id: 'custom-id' })
html
<!-- injected to <head> -->
<style id="custom-id">
.foo { margin-top: 32px; }
</style>
Media query
​

You can pass media attributes as last argument within object.

js
useStyleTag('.foo { margin-top: 32px; }', { media: 'print' })
html
<!-- injected to <head> -->
<style id="vueuse_styletag_1" media="print">
.foo { margin-top: 32px; }
</style>
Source
​

Source • Demo • Docs

Contributors
​
sibbng
Anthony Fu
James Wragg
mrayi
Jelf
Changelog
​
v9.7.0 on 12/16/2022
cfcc2 - fix: allow multiline CSS (#2476)
v9.6.0 on 11/22/2022
94413 - fix: allow use of existing node (#2442)
v8.9.3 on 7/14/2022
71df6 - fix: fix hydration mismatch issue (#1918)
useTextareaAutosize | VueUse

useTextareaAutosize
​
Category
Browser
Export Size
869 B
Last Changed
6 months ago

Automatically update the height of a textarea depending on the content.

Demo
​

source

Type, the textarea will grow:
Usage
​
vue
<script setup lang="ts">
const { textarea, input } = useTextareaAutosize()
</script>

<template>
  <textarea
    ref="textarea"
    v-model="input"
    class="resize-none"
    placeholder="What's on your mind?"
  />
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
leex
JD Solanki
Dominik Pschenitschni
Jelf
Enzo Innocenzi
Changelog
​
v10.2.0 on 6/16/2023
1b0ec - fix: autosize error when changing input asynchronously (#3118)
v10.0.0-beta.0 on 3/14/2023
a3e95 - feat: added styleTarget option to style other element (#2312)
v9.7.0 on 12/16/2022
ea497 - fix: reference
ebd48 - fix: support changes of element width (#2541)
v8.9.0 on 7/6/2022
4c378 - feat: new function (#1756)
useShare | VueUse

useShare
​
Category
Browser
Export Size
546 B
Last Changed
8 months ago

Reactive Web Share API. The Browser provides features that can share content in text or file.

The share method has to be called following a user gesture like a button click. It can’t simply be called on page load for example. That’s in place to help prevent abuse.

Demo
​

source

Web share is not supported in your browser
Usage
​
js
import { useShare } from '@vueuse/core'

const { share, isSupported } = useShare()

function startShare() {
  share({
    title: 'Hello',
    text: 'Hello my friend!',
    url: location.href,
  })
}
Passing a source ref
​

You can pass a ref to it, changes from the source ref will be reflected to your sharing options.

js
import { ref } from 'vue'

const shareOptions = ref < ShareOptions > ({ text: 'foo' })
const { share, isSupported } = useShare(shareOptions)

shareOptions.value.text = 'bar'

share()
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Antério Vieira
Jelf
三咲智子 Kevin Deng
Shinigami
João Eudes Lima
Changelog
​
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue
v8.9.3 on 7/14/2022
106d6 - fix!: rename type ShareOptions to UseShareOptions (#1888)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useScriptTag | VueUse

useScriptTag
​
Category
Browser
Export Size
676 B
Last Changed
8 months ago

Creates a script tag, with support for automatically unloading (deleting) the script tag on unmount.

If a script tag already exists for the given URL, useScriptTag() will not create another script tag, but keep in mind that depending on how you use it, useScriptTag() might have already loaded then unloaded that particular JS file from a previous call of useScriptTag().

Usage
​
TypeScript
ts
import { useScriptTag } from '@vueuse/core'
useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  // on script tag loaded.
  (el: HTMLScriptElement) => {
    // do something
  },
)

The script will be automatically loaded when the component is mounted and removed when the component is unmounted.

Configuration
​

Set manual: true to have manual control over the timing to load the script.

ts
import { useScriptTag } from '@vueuse/core'

const { scriptTag, load, unload } = useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  () => {
    // do something
  },
  { manual: true },
)

// manual controls
await load()
await unload()
Source
​

Source • Docs

Contributors
​
Anthony Fu
Denis Blazhkun
Craig Riley
David B Ludlow
Levi (Nguyễn Lương Huy)
Tomáš Livora
webfansplz
Preston Alvarado
Shinigami
Alex Kozack
Yaël GUILLOUX
Changelog
​
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue
v9.1.0 on 8/4/2022
8f2b7 - fix: normalize src arg (#2030)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useScreenSafeArea | VueUse

useScreenSafeArea
​
Category
Browser
Export Size
1.5 kB
Last Changed
2 years ago

Reactive env(safe-area-inset-*)

Demo
​

source

top:
right:
bottom:
left:
Usage
​

In order to make the page to be fully rendered in the screen, the additional attribute viewport-fit=cover within viewport meta tag must be set firstly, the viewport meta tag may look like this:

html
<meta name='viewport' content='initial-scale=1, viewport-fit=cover'>

Then we could use useScreenSafeArea in the component as shown below:

ts
import { useScreenSafeArea } from '@vueuse/core'

const {
  top,
  right,
  bottom,
  left,
} = useScreenSafeArea()

For further details, you may refer to this documentation: Designing Websites for iPhone X

Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UseScreenSafeArea top right bottom left>content</UseScreenSafeArea>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
vaakian X
Ayaka Rizumu
Jelf
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
useScreenOrientation | VueUse

useScreenOrientation
​
Category
Browser
Export Size
704 B
Last Changed
3 months ago

Reactive Screen Orientation API. It provides web developers with information about the user's current screen orientation.

Demo
​

source

For best results, please use a mobile or tablet device (or use your browser's native inspector to simulate an orientation change)
isSupported: true
Orientation Type: landscape-primary
Orientation Angle: 0
Usage
​
ts
import { useScreenOrientation } from '@vueuse/core'

const {
  isSupported,
  orientation,
  angle,
  lockOrientation,
  unlockOrientation,
} = useScreenOrientation()

To lock the orientation, you can pass an OrientationLockType to the lockOrientation function:

ts
import { useScreenOrientation } from '@vueuse/core'

const {
  isSupported,
  orientation,
  angle,
  lockOrientation,
  unlockOrientation,
} = useScreenOrientation()

lockOrientation('portrait-primary')

and then unlock again, with the following:

ts
unlockOrientation()

Accepted orientation types are one of "landscape-primary", "landscape-secondary", "portrait-primary", "portrait-secondary", "any", "landscape", "natural" and "portrait".

Screen Orientation API MDN

Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Michael J. Roberts
JunaYa
Jelf
Nicolas Hedger
Changelog
​
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
usePreferredReducedMotion | VueUse

usePreferredReducedMotion
​
Category
Browser
Export Size
557 B
Last Changed
last year

Reactive prefers-reduced-motion media query.

Demo
​

source

Preferred Motion:
no-preference
Usage
​
js
import { usePreferredReducedMotion } from '@vueuse/core'

const preferredMotion = usePreferredReducedMotion()
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UsePreferredReducedMotion v-slot="{ motion }">
  Preferred Reduced Motion: {{ motion }}
</UsePreferredReducedMotion>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
丶远方
vaakian X
Zhao
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.1.0 on 8/4/2022
e808b - feat: new function (#2039)
usePreferredLanguages | VueUse

usePreferredLanguages
​
Category
Browser
Export Size
537 B
Last Changed
2 years ago

Reactive Navigator Languages. It provides web developers with information about the user's preferred languages. For example, this may be useful to adjust the language of the user interface based on the user's preferred languages in order to provide better experience.

Demo
​

source

Preferred Languages:
en-US
Usage
​
js
import { usePreferredLanguages } from '@vueuse/core'

const languages = usePreferredLanguages()
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UsePreferredLanguages v-slot="{ languages }">
  Preferred Languages: {{ languages }}
</UsePreferredLanguages>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Antério Vieira
vaakian X
wheat
Alex Kozack
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
usePreferredDark | VueUse

usePreferredDark
​
Category
Browser
Export Size
536 B
Last Changed
2 years ago
Related
useColorMode
useDark

Reactive dark theme preference.

Demo
​

source

Prefers Dark:
true
Usage
​
js
import { usePreferredDark } from '@vueuse/core'

const isDark = usePreferredDark()
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UsePreferredDark v-slot="{ prefersDark }">
  Prefers Dark: {{ prefersDark }}
</UsePreferredDark>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
vaakian X
wheat
Alex Kozack
Antério Vieira
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
usePreferredColorScheme | VueUse

usePreferredColorScheme
​
Category
Browser
Export Size
570 B
Last Changed
2 years ago

Reactive prefers-color-scheme media query.

Demo
​

source

Preferred Color Scheme:
dark
Usage
​
js
import { usePreferredColorScheme } from '@vueuse/core'

const preferredColor = usePreferredColorScheme()
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UsePreferredColorScheme v-slot="{ colorScheme }">
  Preferred Color Scheme: {{ colorScheme }}
</UsePreferredColorScheme>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
丶远方
vaakian X
wheat
Alex Kozack
Le Minh Tri
Antério Vieira
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
usePreferredContrast | VueUse

usePreferredContrast
​
Category
Browser
Export Size
583 B
Last Changed
last year

Reactive prefers-contrast media query.

Demo
​

source

Preferred contrast:
no-preference
Usage
​
js
import { usePreferredContrast } from '@vueuse/core'

const preferredContrast = usePreferredContrast()
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UsePreferredContrast v-slot="{ contrast }">
  Preferred Contrast: {{ contrast }}
</UsePreferredContrast>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
丶远方
vaakian X
Zhao
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.1.1 on 8/23/2022
6db05 - feat: new function (#2040)
usePermission | VueUse

usePermission
​
Category
Browser
Export Size
759 B
Last Changed
last year
Related
useUserMedia

Reactive Permissions API. The Permissions API provides the tools to allow developers to implement a better user experience as far as permissions are concerned.

Demo
​

source

accelerometer: prompt
accessibilityEvents: prompt
ambientLightSensor: prompt
backgroundSync: prompt
camera: prompt
clipboardRead: prompt
clipboardWrite: prompt
gyroscope: prompt
magnetometer: prompt
microphone: prompt
notifications: prompt
paymentHandler: prompt
persistentStorage: prompt
push: prompt
speaker: prompt

Usage
​
js
import { usePermission } from '@vueuse/core'

const microphoneAccess = usePermission('microphone')
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Antério Vieira
Jelf
Guille
Alex Kozack
Nurettin Kaya
Changelog
​
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
usePerformanceObserver | VueUse

usePerformanceObserver
​
Category
Browser
Export Size
536 B
Last Changed
9 months ago

Observe performance metrics.

Demo
​

source

refresh
[]
Usage
​
TypeScript
ts
import { usePerformanceObserver } from '@vueuse/core'
const entrys = ref<PerformanceEntry[]>([])
usePerformanceObserver(
  {
    entryTypes: ['paint'],
  },
  (list) => {
    entrys.value = list.getEntries()
  },
)
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
geekreal
Changelog
​
v10.0.0-beta.0 on 3/14/2023
21536 - feat: new function (#2736)
useObjectUrl | VueUse

useObjectUrl
​
Category
Browser
Export Size
278 B
Last Changed
4 months ago

Reactive URL representing an object.

Creates an URL for the provided File, Blob, or MediaSource via URL.createObjectURL() and automatically releases the URL via URL.revokeObjectURL() when the source changes or the component is unmounted.

Demo
​

source

Select file:
Object URL:
none
Usage
​
html
<script setup>
import { useObjectUrl } from '@vueuse/core'
import { shallowRef } from 'vue'

const file = shallowRef()
const url = useObjectUrl(file)

const onFileChange = (event) => {
  file.value = event.target.files[0]
}
</script>

<template>
  <input type="file" @change="onFileChange" />

  <a :href="url">Open file</a>
</template>
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<template>
  <UseObjectUrl v-slot="url" :object="file">
    <a :href="url">Open file</a>
  </UseObjectUrl>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Andrew Ferreira
vaakian X
BaboonKing
Michael Hüneburg
Changelog
​
v10.3.0 on 7/30/2023
d3f7e - fix: improve parameter type (#3239)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v8.9.0 on 7/6/2022
6ccd0 - feat: new function (#1763)
useMemory | VueUse

useMemory
​
Category
Browser
Export Size
524 B
Last Changed
last year

Reactive Memory Info.

Demo
​

source

Your browser does not support performance memory API
Usage
​
ts
import { useMemory } from '@vueuse/core'

const { isSupported, memory } = useMemory()
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
webfansplz
Changelog
​
v9.0.0-beta.1 on 7/20/2022
4bc0f - fix(useIntervalFn)!: rename type IntervalFnOptions to UseIntervalFnOptions (#1943)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
v8.9.0 on 7/6/2022
6f7cd - fix!: rename type MemoryOptions to UseMemoryOptions (#1605)
useMediaControls | VueUse

useMediaControls
​
Category
Browser
Export Size
2.41 kB
Last Changed
2 months ago

Reactive media controls for both audio and video elements

Demo
​

source

00:00
00:00 / 14:48
Off
English
French
Enter Picture in Picture
Loop
2x
1x
currentTime: 0
duration: 888.035
waiting: false
seeking: false
ended: false
stalled: false
buffered: []
playing: false
rate: 1
volume: 1
muted: false
tracks:
  - id: 0
    label: 'English'
    kind: 'subtitles'
    language: 'en'
    mode: 'showing'
  - id: 1
    label: 'French'
    kind: 'subtitles'
    language: 'fr'
    mode: 'disabled'
    activeCues: null
    cues: null
selectedTrack: 0
supportsPictureInPicture: true
isPictureInPicture: false

Usage
​
Basic Usage
​
html
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useMediaControls } from '@vueuse/core'

const video = ref()
const { playing, currentTime, duration, volume } = useMediaControls(video, { 
  src: 'video.mp4',
})

// Change initial media properties
onMounted(() => {
  volume.value = 0.5
  currentTime.value = 60
})
</script>

<template>
  <video ref="video" />
  <button @click="playing = !playing">Play / Pause</button>
  <span>{{ currentTime }} / {{ duration }}</span>
</template>
Providing Captions, Subtitles, etc...
​

You can provide captions, subtitles, etc in the tracks options of the useMediaControls function. The function will return an array of tracks along with two functions for controlling them, enableTrack, disableTrack, and selectedTrack. Using these you can manage the currently selected track. selectedTrack will be -1 if there is no selected track.

html
<script setup lang="ts">
import { useMediaControls } from '@vueuse/core'
import { ref } from 'vue'
  const video = ref()
  const {
    tracks,
    enableTrack
  } = useMediaControls(video, {
    src: 'video.mp4',
    tracks: [
      {
        default: true,
        src: './subtitles.vtt',
        kind: 'subtitles',
        label: 'English',
        srcLang: 'en',
      },
    ]
  })
</script>

<template>
  <video ref="video" />
  <button v-for="track in tracks" :key="track.id" @click="enableTrack(track)">
    {{ track.label }}
  </button>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Alex Kozack
wheat
Fernando Fernández
Justin Halsall
webfansplz
丶远方
Bryce
CommanderRoot
jelf
rimday
Shinigami
Changelog
​
v10.2.0 on 6/16/2023
0b253 - fix: better representation for "waiting" value (#3072)
v10.1.0 on 4/22/2023
b20aa - fix: apply state when target ref changes (#2999)
v10.0.0-beta.5 on 4/13/2023
cb644 - refactor!: remove isFunction and isString utils
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue
v9.12.0 on 1/29/2023
4ef27 - fix: ended status not updating (#2680)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useMediaQuery | VueUse

useMediaQuery
​
Category
Browser
Export Size
505 B
Last Changed
4 months ago

Reactive Media Query. Once you've created a MediaQueryList object, you can check the result of the query or receive notifications when the result changes.

Demo
​

source

isLargeScreen: true
prefersDark: true

Usage
​
js
import { useMediaQuery } from '@vueuse/core'

const isLargeScreen = useMediaQuery('(min-width: 1024px)')
const isPreferredDark = useMediaQuery('(prefers-color-scheme: dark)')
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Antério Vieira
Indrek Ardel
Zhousg
Young
Jelf
Dominik Freier
webfansplz
Eureka
karma
Alex Kozack
Jacob Clevenger
Changelog
​
v10.3.0 on 7/30/2023
f3969 - fix: only add/remove event listeners on query change (#3236)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef
v10.0.0-beta.3 on 4/13/2023
4e7b0 - fix(useWindowSize)!: use media query instead of orientationchange listener (#2919)
v9.3.0 on 9/26/2022
33098 - feat: allow query to be a ref (#2178)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
v8.8.1 on 7/6/2022
60f9a - fix: check if window.matchMedia is a function (#1765)
v8.8.0 on 7/6/2022
5a64c - fix: strict isSupported check
useGamepad | VueUse

useGamepad
​
Category
Browser
Export Size
1.25 kB
Last Changed
6 months ago

Provides reactive bindings for the Gamepad API.

Demo
​

source

Gamepad is not supported on this device.
It seems your device does not support the Gamepad API. Check here for a list supported devices.
Usage
​

Due to how the Gamepad API works, you must interact with the page using the gamepad before it will be detected.

html
<script setup>
import { computed } from 'vue'
import { useGamepad } from '@vueuse/core'

const { isSupported, gamepads } = useGamepad()
const gamepad = computed(() => gamepads.find(g => g.mapping === 'standard'))
</script>

<template>
  <span>
    {{ gamepad.id }}
  <span>
</template>
Gamepad Updates
​

Currently the Gamepad API does not have event support to update the state of the gamepad. To update the gamepad state, requestAnimationFrame is used to poll for gamepad changes. You can control this polling by using the pause and resume functions provided by useGamepad

ts
import { useGamepad } from '@vueuse/core'

const { pause, resume, gamepads } = useGamepad()

pause()

// gamepads object will not update

resume()

// gamepads object will update on user input
Gamepad Connect & Disconnect Events
​

The onConnected and onDisconnected events will trigger when a gamepad is connected or disconnected.

ts
const { gamepads, onConnected, onDisconnected } = useGamepad()

onConnected((index) => {
  console.log(`${gamepads.value[index].id} connected`)
})

onDisconnected((index) => {
  console.log(`${index} disconnected`)
})
Vibration
​

The Gamepad Haptics API is sparse, so check the compatibility table before using.

ts
import { computed } from 'vue'

const supportsVibration = computed(() => gamepad.hapticActuators.length > 0)
function vibrate() {
  if (supportsVibration.value) {
    const actuator = gamepad.hapticActuators[0]
    actuator.playEffect('dual-rumble', {
      startDelay: 0,
      duration: 1000,
      weakMagnitude: 1,
      strongMagnitude: 1,
    })
  }
}
Mappings
​

To make the Gamepad API easier to use, we provide mappings to map a controller to a controllers button layout.

Xbox360 Controller
​
html
<script setup>
import { mapGamepadToXbox360Controller } from '@vueuse/core'

const controller = mapGamepadToXbox360Controller(gamepad)
</script>

<template>
  <span>{{ controller.buttons.a.pressed }}</span>
  <span>{{ controller.buttons.b.pressed }}</span>
  <span>{{ controller.buttons.x.pressed }}</span>
  <span>{{ controller.buttons.y.pressed }}</span>
</template>

Currently there are only mappings for the Xbox 360 controller. If you have controller you want to add mappings for, feel free to open a PR for more controller mappings!

Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
wheat
Jelf
丶远方
三咲智子
Changelog
​
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
useImage | VueUse

useImage
​
Category
Browser
Export Size
1.39 kB
Last Changed
2 months ago

Reactive load an image in the browser, you can wait the result to display it or show a fallback.

Demo
​

source

Loading...
ChangeCreate Error
Usage
​
html
<script setup>
import { useImage } from '@vueuse/core'

const avatarUrl = 'https://place.dog/300/200'
const { isLoading } = useImage({ src: avatarUrl })
</script>

<template>
  <span v-if="isLoading">Loading</span>
  <img v-else :src="avatarUrl">
</template>
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<template>
  <UseImage src="https://place.dog/300/200">
    <template #loading>
      Loading..
    </template>

    <template #error>
      Failed
    </template>
  </UseImage>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
Riley Gelwicks
btea
François M
vaakian X
Lúcio Rubens
Changelog
​
v10.2.0 on 6/16/2023
04d32 - feat: support referrerPolicy option (#3132)
v10.1.1 on 5/2/2023
c110a - feat: support more image properties (#3021)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v8.9.2 on 7/12/2022
24ede - fix(useAsyncState)!: rename type AsyncStateOptions to UseAsyncStateOptions (#1809)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
v8.7.0 on 6/16/2022
f4b37 - feat: new function (#1460)
useFullscreen | VueUse

useFullscreen
​
Category
Browser
Export Size
1.05 kB
Last Changed
2 months ago

Reactive Fullscreen API. It adds methods to present a specific Element (and its descendants) in full-screen mode, and to exit full-screen mode once it is no longer needed. This makes it possible to present desired content—such as an online game—using the user's entire screen, removing all browser user interface elements and other applications from the screen until full-screen mode is shut off.

Demo
​

source

Go Fullscreen
Usage
​
js
import { useFullscreen } from '@vueuse/core'

const { isFullscreen, enter, exit, toggle } = useFullscreen()

Fullscreen specified element. Some platforms (like iOS's Safari) only allow fullscreen on video elements.

TypeScript
ts
const el = ref<HTMLElement | null>(null)
const { isFullscreen, enter, exit, toggle } = useFullscreen(el)
html
<video ref='el'>
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UseFullscreen v-slot="{ toggle }">
  <video />
  <button @click="toggle">
    Go Fullscreen
  </button>
</UseFullscreen>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Fernando Fernández
wheat
Antério Vieira
tawen
zaqvil
Yvan Zhu
vaakian X
Jelf
webfansplz
Shinigami
Alex Kozack
Changelog
​
v10.2.1 on 6/28/2023
14edb - fix: skip exiting when not in fullscreen mode (#3144)
v10.1.0 on 4/22/2023
4a7a1 - fix: isFullscreen handling for mutliple fullscreen elements (#3000)
v10.0.0-beta.3 on 4/13/2023
2e467 - fix!: better cross-platform compatibility (#2915)
v10.0.0-beta.0 on 3/14/2023
9d394 - fix: handle Safari iOS (#2822)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
useFileDialog | VueUse

useFileDialog
​
Category
Browser
Export Size
707 B
Last Changed
3 weeks ago

Open file dialog with ease.

Demo
​

source

Choose filesReset
Usage
​
TypeScript
ts
import { useFileDialog } from '@vueuse/core'
const { files, open, reset, onChange } = useFileDialog({
  accept: 'image/*', // Set to accept only image files
  directory: true, // Select directories instead of files if set true
})
onChange((files) => {
  /** do something with files */
})
html
<template>
  <button type="button" @click="open">Choose file</button>
</template>
Source
​

Source • Demo • Docs

Contributors
​
huiliangShen
Sandra Rodgers
Damian Głowala
zaqvil
丶远方
1SZX1
ZHAO Jinxiang
Max
Anthony Fu
Robert Soriano
Changelog
​
v10.6.0 on 11/9/2023
cefca - feat: add directory parameters (#3513)
v10.2.0 on 6/16/2023
6d847 - feat: add a parameter reset (#3059)
v10.0.0-beta.1 on 3/23/2023
5e697 - feat: add listener for file change events (#2893)
v9.2.0 on 9/5/2022
c463a - fix: choose file not work on mobile (#2080)
v8.9.4 on 7/17/2022
46192 - fix: explict UseFileDialogReturn type (#1927)
v8.9.1 on 7/8/2022
58a45 - fix: SSR compatible, close #1788
v8.9.0 on 7/6/2022
44526 - feat: new function (#1218)
useFavicon | VueUse

useFavicon
​
Category
Browser
Export Size
362 B
Last Changed
2 months ago

Reactive favicon

Demo
​

source

Change favicon to
VueVueUse
Usage
​
js
import { useFavicon } from '@vueuse/core'

const icon = useFavicon()

icon.value = 'dark.png' // change current icon
Passing a source ref
​

You can pass a ref to it, changes from of the source ref will be reflected to your favicon automatically.

js
import { computed } from 'vue'
import { useFavicon, usePreferredDark } from '@vueuse/core'

const isDark = usePreferredDark()
const favicon = computed(() => isDark.value ? 'dark.png' : 'light.png')

useFavicon(favicon)

When a source ref is passed, the return ref will be identical to the source ref

ts
const source = ref('icon.png')
const icon = useFavicon(source)

console.log(icon === source) // true
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Antério Vieira
babu-ch
azaleta
Mikhailov Nikita
Jelf
Alex Kozack
Changelog
​
v10.5.0 on 10/7/2023
d1fcc - feat: Add link tag if it doesn't exist (#3444)
v10.0.0-beta.5 on 4/13/2023
cb644 - refactor!: remove isFunction and isString utils
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef
v9.2.0 on 9/5/2022
df718 - fix: improve type overload (#2123)
v9.1.0 on 8/4/2022
06e26 - fix: writable return type (#2036)
v8.9.3 on 7/14/2022
99e07 - fix!: rename type FaviconOptions to UseFaviconOptions (#1865)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useEyeDropper | VueUse

useEyeDropper
​
Category
Browser
Export Size
314 B
Last Changed
2 months ago

Reactive EyeDropper API

Demo
​

source

isSupported: true
sRGBHex:
Open Eye Dropper
Usage
​
ts
import { useEyeDropper } from '@vueuse/core'

const { isSupported, open, sRGBHex } = useEyeDropper()
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UseEyeDropper v-slot="{ isSupported, sRGBHex, open }">
  <button :disabled="!isSupported" @click="open">
    sRGBHex: {{ sRGBHex }}
  </button>
</UseEyeDropper>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
vaakian X
wheat
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
useDark | VueUse

useDark
​
Category
Browser
Export Size
3.03 kB
Last Changed
7 months ago
Related
useColorMode
usePreferredDark
useStorage

Reactive dark mode with auto data persistence.

Learn useDark with this FREE video lesson from Vue School!
Demo
​

source

Dark
Basic Usage
​
js
import { useDark, useToggle } from '@vueuse/core'

const isDark = useDark()
const toggleDark = useToggle(isDark)
Behavior
​

useDark combines with usePreferredDark and useStorage On start up, it reads the value from localStorage/sessionStorage (the key is configurable) to see if there is a user configured color scheme, if not, it will use users' system preferences. When you change the isDark ref, it will update the corresponding element's attribute and then store the preference to storage (default key: vueuse-color-scheme) for persistence.

Please note useDark only handles the DOM attribute changes for you to apply proper selector in your CSS. It does NOT handle the actual style, theme or CSS for you.

Configuration
​

By default, it uses Tailwind CSS favored dark mode, which enables dark mode when class dark is applied to the html tag, for example:

html
<!--light-->
<html> ... </html>

<!--dark-->
<html class="dark"> ... </html>

Still, you can also customize it to make it work with most CSS frameworks.

For example:

ts
const isDark = useDark({
  selector: 'body',
  attribute: 'color-scheme',
  valueDark: 'dark',
  valueLight: 'light',
})

will work like

html
<!--light-->
<html>
  <body color-scheme="light"> ... </body>
</html>

<!--dark-->
<html>
  <body color-scheme="dark"> ... </body>
</html>

If the configuration above still does not fit your needs, you can use theonChanged option to take full control over how you handle updates.

TypeScript
ts
const isDark = useDark({
  onChanged(dark: boolean) {
    // update the dom, call the API or something
  },
})
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UseDark v-slot="{ isDark, toggleDark }">
  <button @click="toggleDark()">
    Is Dark: {{ isDark }}
  </button>
</UseDark>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
wheat
Waleed Khaled
Daniel Weaver
vaakian X
Kevin Cole
vaakian X
云游君
Mehran Mirshekaran
Máximo Mussini
Pig Fang
Alex Kozack
ordago
Le Minh Tri
Changelog
​
v10.1.0 on 4/22/2023
a1bef - feat(useColorMode): expose state to the ref, deprecated emitAuto (#2980)
v10.0.0-beta.2 on 3/28/2023
d6d35 - feat: passthrough default handler from useColorSchema (#2866)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
useCssVar | VueUse

useCssVar
​
Category
Browser
Export Size
820 B
Last Changed
6 months ago

Manipulate CSS variables

Demo
​

source

Sample text, #7fa998
Change Color
Sample text, --color: #7fa998
Change Color Variable
Usage
​
js
import { useCssVar } from '@vueuse/core'

const el = ref(null)
const color1 = useCssVar('--color', el)

const elv = ref(null)
const key = ref('--color')
const colorVal = useCssVar(key, elv)

const someEl = ref(null)
const color2 = useCssVar('--color', someEl, { initialValue: '#eee' })
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
丶远方
Antério Vieira
Waleed Khaled
木荣
JD Solanki
btea
Alex Kozack
Changelog
​
v10.2.0 on 6/16/2023
9d34a - fix: observe changes based on element class list (#3131)
v10.0.2 on 4/14/2023
7d001 - fix: module reference, close #2972
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue
v10.0.0-beta.0 on 3/14/2023
ae6e1 - feat: introduce observe option (#2800)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
v8.8.0 on 7/6/2022
31417 - fix: remove spaces at both ends (#1741)
v8.6.0 on 5/31/2022
bbb83 - feat: support initialValue (#1619)
useColorMode | VueUse

useColorMode
​
Category
Browser
Export Size
2.89 kB
Last Changed
2 months ago
Related
useDark
usePreferredDark
useStorage

Reactive color mode (dark / light / customs) with auto data persistence.

Demo
​

source

Auto← Click to change the color mode
Basic Usage
​
js
import { useColorMode } from '@vueuse/core'

const mode = useColorMode() // Ref<'dark' | 'light'>

By default, it will match with users' browser preference using usePreferredDark (a.k.a auto mode). When reading the ref, it will by default return the current color mode (dark, light or your custom modes). The auto mode can be included in the returned modes by enabling the emitAuto option. When writing to the ref, it will trigger DOM updates and persist the color mode to local storage (or your custom storage). You can pass auto to set back to auto mode.

ts
mode.value // 'dark' | 'light'

mode.value = 'dark' // change to dark mode and persist

mode.value = 'auto' // change to auto mode
Config
​
js
import { useColorMode } from '@vueuse/core'

const mode = useColorMode({
  attribute: 'theme',
  modes: {
    // custom colors
    dim: 'dim',
    cafe: 'cafe',
  },
}) // Ref<'dark' | 'light' | 'dim' | 'cafe'>
Advanced Usage
​

You can also explicit access to the system preference and storaged user override mode.

js
import { useColorMode } from '@vueuse/core'

const { system, store } = useColorMode()

system.value // 'dark' | 'light'
store.value // 'dark' | 'light' | 'auto'

const myColorMode = computed(() => store.value === 'auto' ? system.value : store.value)
Component Usage
​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

html
<UseColorMode v-slot="{ mode }">
  <button @click="mode = mode === 'dark' ? 'light' : 'dark'">
    Mode {{ mode }}
  </button>
</UseColorMode>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Waleed Khaled
Dominik Freier
wheat
Jason Liang
Yang
丶远方
ntnyq
vaakian X
sun0day
vaakian X
Jelf
Andreas Weber
Andrej Hýll
Changelog
​
v10.2.0 on 6/16/2023
78a3a - feat: disableTransition support pseudo-elements (#3129)
v10.1.0 on 4/22/2023
a1bef - feat: expose state to the ref, deprecated emitAuto (#2980)
adbbb - fix: element ref support, close #3003
v10.0.0-beta.4 on 4/13/2023
5c82c - fix!: enable disableTransition by default
d150c - feat: expose system and store ref, close #2023
02ccc - feat: support passing element as selector (#2760)
v10.0.0-beta.0 on 3/14/2023
320ab - feat(useDark, useColorMode): introduce disableTransition option
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.0.1 on 7/29/2022
98f8b - fix: when emitAuto is true, onChanged does not trigger when preferredMode changed (#2004)
v9.0.0-beta.2 on 7/24/2022
fcaf9 - feat: new initialValue option
v8.9.3 on 7/14/2022
499f6 - fix(useStorage)!: rename type StorageOptions to UseStorageOptions (#1867)
v8.9.0 on 7/6/2022
092cb - fix: resolve auto to preferred mode internally (#1766)
v8.8.0 on 7/6/2022
d67d9 - feat: add option to return auto mode (#1627)
useEventListener | VueUse

useEventListener
​
Category
Browser
Export Size
467 B
Last Changed
3 months ago

Use EventListener with ease. Register using addEventListener on mounted, and removeEventListener automatically on unmounted.

Usage
​
js
import { useEventListener } from '@vueuse/core'

useEventListener(document, 'visibilitychange', (evt) => {
  console.log(evt)
})

You can also pass a ref as the event target, useEventListener will unregister the previous event and register the new one when you change the target.

TypeScript
ts
import { useEventListener } from '@vueuse/core'
const element = ref<HTMLDivElement>()
useEventListener(element, 'keydown', (e) => {
  console.log(e.key)
})
html
<template>
  <div v-if="cond" ref="element">Div1</div>
  <div v-else ref="element">Div2</div>
</template>

You can also call the returned to unregister the listener.

ts
import { useEventListener } from '@vueuse/core'

const cleanup = useEventListener(document, 'keydown', (e) => {
  console.log(e.key)
})

cleanup() // This will unregister the listener.

Note if your components also run in SSR (Server Side Rendering), you might get errors (like document is not defined) because DOM APIs like document and window are not available in Node.js. To avoid that you can put the logic inside onMounted hook.

ts
// onMounted will only be called in the client side, so it guarantees the DOM APIs are available.
onMounted(() => {
  useEventListener(document, 'keydown', (e) => {
    console.log(e.key)
  })
})
Source
​

Source • Docs

Contributors
​
Anthony Fu
丶远方
Julien Le Coupanec
Michael J. Roberts
James Garbutt
vaakian X
sun0day
Alejandro Arevalo
Jelf
Alex Kozack
lstoeferle
Antério Vieira
Changelog
​
v10.4.1 on 8/28/2023
3ef59 - fix: immutable options on removal, close #2825 (#3346)
v10.3.0 on 7/30/2023
4f414 - fix: improved useEventListener overload (#3246)
v10.0.0-beta.5 on 4/13/2023
cb644 - refactor!: remove isFunction and isString utils
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue
v9.13.0 on 2/18/2023
103d6 - feat: support reactive options
v9.10.0 on 1/3/2023
07f20 - feat(useActiveElement): support shadow roots (#2592)
v9.5.0 on 11/9/2022
ab0ee - feat: accept multiple events or listeners (#2180)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)