matijao/webdev huggingface dataset:
useTimestamp | VueUse

useTimestamp
​
Category
Animation
Export Size
817 B
Last Changed
last year

Reactive current timestamp

Demo
​

source

Timestamp: 1701206224633
Usage
​
js
import { useTimestamp } from '@vueuse/core'

const timestamp = useTimestamp({ offset: 0 })
js
const { timestamp, pause, resume } = useTimestamp({ controls: true })
Component Usage
​

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

html
<UseTimestamp v-slot="{ timestamp, pause, resume }">
  Current Time: {{ timestamp }}
  <button @click="pause()">Pause</button>
  <button @click="resume()">Resume</button>
</UseTimestamp>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
vaakian X
sun0day
Waleed Khaled
sun0day
Jelf
Scott Bedard
Shinigami
wheat
Alex Kozack
Antério Vieira
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.3.0 on 9/26/2022
33dbc - feat: optional callback for useInterval, useTimeout & useTimestamp (#2240)
v8.9.3 on 7/14/2022
98985 - fix!: rename type TimestampOptions to UseTimestampOptions (#1892)
useRafFn | VueUse

useRafFn
​
Category
Animation
Export Size
342 B
Last Changed
2 months ago

Call function on every requestAnimationFrame. With controls of pausing and resuming.

Demo
​

source

Count: 5
pauseresume
Usage
​
js
import { ref } from 'vue'
import { useRafFn } from '@vueuse/core'

const count = ref(0)

const { pause, resume } = useRafFn(() => {
  count.value++
  console.log(count.value)
})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
max.lee
Hayk Khachatryan
Dan Rose
Enzo Innocenzi
Jelf
he yifan
Alex Kozack
Jacob Clevenger
Scott Bedard
Antério Vieira
Changelog
​
v10.5.0 on 10/7/2023
8e4c0 - feat: option fpsLimit (#3459)
v10.2.1 on 6/28/2023
cf6eb - fix: set initial delta to zero (#3150)
v9.12.0 on 1/29/2023
39183 - feat(useRafFn, useIntervalFn, useTimeoutFn): make status readonly (#2685)
v9.7.0 on 12/16/2022
692d0 - feat: add delta and timestamp (#2493)
v8.9.3 on 7/14/2022
c3dd7 - fix!: rename type RafFnOptions to UseRafFnOptions (#1887)
useAnimate | VueUse

useAnimate
​
Category
Animation
Export Size
1.56 kB
Last Changed
4 months ago

Reactive Web Animations API.

Demo
​

source

VueUse useAnimate

pausereversefinishcancel
startTime: 1876.8
currentTime: 233.30000000000007
playbackRate: 1
playState: 'running'
replaceState: 'active'
pending: false

Usage
​
Basic Usage
​

The useAnimate function will return the animate and its control function.

html
<template>
  <span ref="el" style="display:inline-block">useAnimate</span>
</template>

<script setup>
import { ref } from 'vue'
import { useAnimate } from '@vueuse/core'

const el = ref()
const {
  isSupported,
  animate,

  // actions
  play,
  pause,
  reverse,
  finish,
  cancel,

  // states
  pending,
  playState,
  replaceState,
  startTime,
  currentTime,
  timeline,
  playbackRate,
} = useAnimate(el, { transform: 'rotate(360deg)' }, 1000)
</script>
Custom Keyframes
​

Either an array of keyframe objects, or a keyframe object, or a ref. See Keyframe Formats for more details.

ts
const keyframes = { transform: 'rotate(360deg)' }
// Or
const keyframes = [
  { transform: 'rotate(0deg)' },
  { transform: 'rotate(360deg)' },
]
// Or
const keyframes = ref([
  { clipPath: 'circle(20% at 0% 30%)' },
  { clipPath: 'circle(20% at 50% 80%)' },
  { clipPath: 'circle(20% at 100% 30%)' },
])

useAnimate(el, keyframes, 1000)
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
丶远方
jack zhang
qiang
Changelog
​
v10.0.0-beta.4 on 4/13/2023
bcf5d - feat: new function (#2109)
useNow | VueUse

useNow
​
Category
Animation
Export Size
788 B
Last Changed
2 years ago

Reactive current Date instance.

Demo
​

source

Now: Tue Nov 28 2023 22:17:03 GMT+0100 (Central European Standard Time)
Usage
​
js
import { useNow } from '@vueuse/core'

const now = useNow()
js
const { now, pause, resume } = useNow({ controls: true })
Component Usage
​

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

html
<UseNow v-slot="{ now, pause, resume }">
  Now: {{ now }}
  <button @click="pause()">Pause</button>
  <button @click="resume()">Resume</button>
</UseNow>
Source
​

Source • Demo • Docs

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

useEventSource
​
Category
Network
Export Size
679 B
Last Changed
7 months ago

An EventSource or Server-Sent-Events instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format.

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

const { status, data, error, close } = useEventSource('https://event-source-url')
State	Type	Description
status	Ref<string>	A read-only value representing the state of the connection. Possible values are CONNECTING (0), OPEN (1), or CLOSED (2)
data	Ref<string | null>	Reference to the latest data received via the EventSource, can be watched to respond to incoming messages
eventSource	Ref<EventSource | null>	Reference to the current EventSource instance
Method	Signature	Description
close	() => void	Closes the EventSource connection gracefully.
Source
​

Source • Docs

Contributors
​
Anthony Fu
Antério Vieira
Michael J. Roberts
丶远方
Jelf
Shinigami
江麻妞
Shinigami
Alex Kozack
Johnson Chen
Charles
Changelog
​
v10.1.1 on 5/2/2023
790bc - feat: allow optional string | URL type for url arg (#3035)
v8.9.3 on 7/14/2022
a5192 - fix!: return type should be UseEventSourceReturn (#1864)
useUserMedia | VueUse

useUserMedia
​
Category
Sensors
Export Size
569 B
Last Changed
8 months ago
Related
useDevicesList
useDisplayMedia
usePermission

Reactive mediaDevices.getUserMedia streaming.

Demo
​

source

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

const { stream, start } = useUserMedia()

start()
ts
const video = document.getElementById('video')

watchEffect(() => {
  // preview on a video element
  video.srcObject = stream.value
})
Devices
​
js
import { useDevicesList, useUserMedia } from '@vueuse/core'

const {
  videoInputs: cameras,
  audioInputs: microphones,
} = useDevicesList({
  requestPermissions: true,
})
const currentCamera = computed(() => cameras.value[0]?.deviceId)
const currentMicrophone = computed(() => microphones.value[0]?.deviceId)

const { stream } = useUserMedia({
  constraints: {
    video: { deviceId: currentCamera },
    audio: { deviceId: currentMicrophone, }
  }
})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Martin
Jelf
wheat
Shinigami
Alex Kozack
Changelog
​
v10.0.0-beta.3 on 4/13/2023
85468 - fix!: remove deprecated apis
v10.0.0-beta.0 on 3/14/2023
8f2a3 - feat!: add constraints - remove deviceIds (#2032)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
useTextSelection | VueUse

useTextSelection
​
Category
Sensors
Export Size
681 B
Last Changed
4 months ago

Reactively track user text selection based on Window.getSelection.

Demo
​

source

You can select any text on the page.

Selected Text:
No selected

Selected rects:
[]

Usage
​
html
<template>
  <p>{{state.text}}</p>
</template>

<script setup lang="ts">
  import { useTextSelection } from '@vueuse/core'
  const state = useTextSelection()
</script>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Lehoczky Zoltán
wheat
Jelf
webfansplz
Changelog
​
No recent changes
useSwipe | VueUse

useSwipe
​
Category
Sensors
Export Size
996 B
Last Changed
4 months ago

Reactive swipe detection based on TouchEvents.

Demo
​

source

Reset

Swipe right

Direction: none
lengthX: 0 | lengthY: 0

Usage
​
html
<template>
  <div ref="el">
    Swipe here
  </div>
</template>

<script>
  setup() {
    const el = ref(null)
    const { isSwiping, direction } = useSwipe(el)

    return { el, isSwiping, direction }
  } 
</script>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
丶远方
Amirreza Zarkesh
lstoeferle
Alexey Istomin
Jelf
云游君
Shinigami
Alex Kozack
Changelog
​
v10.1.0 on 4/22/2023
af3ca - fix: ignore multiple touches (#2996)
995aa - fix: ignore multiple touches (#2994)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
v10.0.0-beta.0 on 3/14/2023
f285c - fix!: use literal for swipe direction instead of enum
08c21 - feat(useSwipe, usePointerSwipe, useTransition): improve tree-shaking (#2863)
v8.9.3 on 7/14/2022
d7052 - fix!: rename type SwipeOptions to UseSwipeOptions and SwipeReturn to UseSwipeReturn (#1891)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useParallax | VueUse

useParallax
​
Category
Sensors
Export Size
1.5 kB
Last Changed
last year

Create parallax effect easily. It uses useDeviceOrientation and fallback to useMouse if orientation is not supported.

Demo
​

source

roll: 0.5
tilt: -0.5
source: mouse

Credit of images to Jarom Vogel
Usage
​
html
<div ref='container'>
</div>
js
import { useParallax } from '@vueuse/core'

export default {
  setup() {
    const container = ref(null)
    const { tilt, roll, source } = useParallax(container)

    return {
      container,
    }
  },
}
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Antério Vieira
Jelf
wheat
Changelog
​
v8.9.3 on 7/14/2022
e4b5b - fix!: rename type ParallaxOptions to UseParallaxOptions and ParallaxReturn to UseParallaxReturn (#1885)
useSpeechRecognition | VueUse

useSpeechRecognition
​
Category
Sensors
Export Size
694 B
Last Changed
8 months ago

Reactive SpeechRecognition.

Can I use?

Demo
​

source

English (US)
French
Spanish
Press and talk
Usage
​
ts
import { useSpeechRecognition } from '@vueuse/core'

const {
  isSupported,
  isListening,
  isFinal,
  result,
  start,
  stop,
} = useSpeechRecognition()
Options
​

The following shows the default values of the options, they will be directly passed to SpeechRecognition API.

ts
useSpeechRecognition({
  lang: 'en-US',
  interimResults: true,
  continuous: true,
})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
Mark Noonan
vaakian X
wheat
Joe Maylor
Shinigami
Alex Kozack
EGGSY
Antério Vieira
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.3 on 7/14/2022
36f33 - fix!: rename type SpeechRecognitionOptions to UseSpeechRecognitionOptions (#1889)
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)
useScrollLock | VueUse

useScrollLock
​
Category
Sensors
Export Size
915 B
Last Changed
3 weeks ago

Lock scrolling of the element.

Demo
​

source

TopLeft
BottomLeft
TopRight
BottomRight
Scroll Me
isLocked false
Lock
Usage
​
html
<script setup lang="ts">
import { useScrollLock } from '@vueuse/core'

const el = ref<HTMLElement | null>(null)
const isLocked = useScrollLock(el)

isLocked.value = true // lock
isLocked.value = false // unlock
</script>

<template>
  <div ref="el"></div>
</template>
Directive Usage
​

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

html
<script setup lang="ts">
import { vScrollLock } from '@vueuse/components'
const data = ref([1, 2, 3, 4, 5, 6])
const isLocked = ref(false)
const toggleLock = useToggle(isLocked)
</script>

<template>
  <div v-scroll-lock="isLocked">
    <div v-for="item in data" :key="item">
      {{ item }}
    </div>
  </div>
  <button @click="toggleLock()">
    Toggle lock state
  </button>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
webfansplz
Ayaka Rizumu
Doctorwu
Zhaolin Liang
Valery
Dominik Pschenitschni
Robin Scholz
Jelf
wheat
Changelog
​
v10.6.0 on 11/9/2023
03866 - fix(onScrollLock): cache the el initial overflow value (#3527)
v10.4.0 on 8/25/2023
8acdb - fix: support using window or document (#3319)
v10.2.0 on 6/16/2023
cdc28 - fix: fix scrollable children check (#3065)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef
0a72b - feat(toValue): rename resolveUnref to toValue
v9.13.0 on 2/18/2023
7e590 - fix: detect parent with overflow auto (#2699)
v9.10.0 on 1/3/2023
c9a9a - fix: fix iOS touchmove bug (#2362)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
usePointerSwipe | VueUse

usePointerSwipe
​
Category
Sensors
Export Size
1.04 kB
Last Changed
8 months ago

Reactive swipe detection based on PointerEvents.

Demo
​

source

Reset

Swipe

Usage
​
html
<script setup>
import { ref } from 'vue'
import { usePointerSwipe } from '@vueuse/core'

const el = ref(null)
const { isSwiping, direction } = usePointerSwipe(el)
</script>

<template>
  <div ref="el">
    Swipe here
  </div>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jeffrey Li
Alexey Istomin
丶远方
Curt Grimes
sun0day
Jelf
wheat
MinatoHikari
Ilya Komichev
lstoeferle
Changelog
​
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.0 on 3/14/2023
f285c - fix(useSwipe)!: use literal for swipe direction instead of enum
08c21 - feat(useSwipe, usePointerSwipe, useTransition): improve tree-shaking (#2863)
v9.5.0 on 11/9/2022
862d1 - fix: handle secondary clicks properly (#2379)
v8.9.3 on 7/14/2022
81ff5 - fix!: rename type PointerSwipeOptions to UsePointerSwipeOptions and PointerSwipeReturn to UsePointerSwipeReturn (#1886)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
usePointer | VueUse

usePointer
​
Category
Sensors
Export Size
1.14 kB
Last Changed
2 months ago

Reactive pointer state.

Demo
​

source

{
  "x": 0,
  "y": 0,
  "pointerId": 0,
  "pressure": 0,
  "tiltX": 0,
  "tiltY": 0,
  "width": 0,
  "height": 0,
  "twist": 0,
  "pointerType": null,
  "isInside": false
}
Basic Usage
​
js
import { usePointer } from '@vueuse/core'

const { x, y, pressure, pointerType } = usePointer()
Component Usage
​

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

By default, the component will track the pointer on window

html
<UsePointer v-slot="{ x, y }">
  x: {{ x }}
  y: {{ y }}
</UsePointer>

To track local position in the element, set target="self":

html
<UsePointer target="self" v-slot="{ x, y }">
  x: {{ x }}
  y: {{ y }}
</UsePointer>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
cunzaizhuyi
丶远方
vaakian X
Jelf
zz
Changelog
​
v10.3.0 on 7/30/2023
ee425 - fix: add pointerup event for pressure field (#3217)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
usePointerLock | VueUse

usePointerLock
​
Category
Sensors
Export Size
1.36 kB
Last Changed
11 months ago

Reactive pointer lock.

Demo
​

source

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

const { isSupported, lock, unlock, element, triggerElement } = usePointerLock()
Component Usage
​

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

html
<UsePointerLock v-slot="{ lock }">
  <canvas />
  <button @click="lock">
    Lock Pointer on Canvas
  </button>
</UsePointerLock>
Source
​

Source • Demo • Docs

Contributors
​
Sergey Danilchenko
Changelog
​
v9.11.0 on 1/17/2023
ae69f - feat: new function (#2590)
usePageLeave | VueUse

usePageLeave
​
Category
Sensors
Export Size
576 B
Last Changed
2 years ago

Reactive state to show whether the mouse leaves the page.

Demo
​

source

{
  "isLeft": false
}
Usage
​
js
import { usePageLeave } from '@vueuse/core'

const isLeft = usePageLeave()
Component Usage
​

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

html
<UsePageLeave v-slot="{ isLeft }">
  Has Left Page: {{ isLeft }}
</UsePageLeave>
Source
​

Source • Demo • Docs

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

useOnline
​
Category
Sensors
Export Size
830 B
Last Changed
2 years ago

Reactive online state. A wrapper of useNetwork

Demo
​

source

Disconnect your network to see changes
Status: Online
Usage
​
js
import { useOnline } from '@vueuse/core'

const online = useOnline()
Component Usage
​

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

html
<UseOnline v-slot="{ isOnline }">
  Is Online: {{ isOnline }}
</UseOnline>
Source
​

Source • Demo • Docs

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

useNavigatorLanguage
​
Category
Sensors
Export Size
632 B
Last Changed
8 months ago

Reactive navigator.language.

Demo
​

source

Supported: true

Navigator Language:
en-US
Usage
​
TypeScript
ts
import { defineComponent, ref } from 'vue'
import { useNavigatorLanguage } from '@vueuse/core'
export default defineComponent({
  setup() {
    const { language } = useNavigatorLanguage()
    watch(language, () => {
      // Listen to the value changing
    })
    return {
      language,
    }
  },
})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
vaakian X
Jelf
WuLianN
Michael J. Roberts
Changelog
​
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
useMousePressed | VueUse

useMousePressed
​
Category
Sensors
Export Size
679 B
Last Changed
2 months ago

Reactive mouse pressing state. Triggered by mousedown touchstart on target element and released by mouseup mouseleave touchend touchcancel on window.

Demo
​

source

pressed: false
sourceType: null

Tracking on Entire page
Basic Usage
​
js
import { useMousePressed } from '@vueuse/core'

const { pressed } = useMousePressed()

Touching is enabled by default. To make it only detects mouse changes, set touch to false

js
const { pressed } = useMousePressed({ touch: false })

To only capture mousedown and touchstart on specific element, you can specify target by passing a ref of the element.

html
<template>
  <div ref="el">
    Only clicking on this element will trigger the update.
  </div>
</template>

<script>
import { ref } from 'vue'
import { useMousePressed } from '@vueuse/core'

export default {
  setup() {
    const el = ref(null)

    const { pressed } = useMousePressed({ target: el })

    return {
      el,
      pressed,
    }
  }
}
</script>
Component Usage
​

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

html
<UseMousePressed v-slot="{ pressed }">
  Is Pressed: {{ pressed }}
</UseMousePressed>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
wheat
丶远方
Jonas Schade
RAX7
ByMykel
vaakian X
MinatoHikari
Marshall Thompson
Shinigami
Alex Kozack
Changelog
​
v10.5.0 on 10/7/2023
d5c81 - feat: add capture option (#3392)
v10.1.0 on 4/22/2023
4bb5b - feat(useMouse): support custom event extractor (#2991)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
useNetwork | VueUse

useNetwork
​
Category
Sensors
Export Size
814 B
Last Changed
last year

Reactive Network status. The Network Information API provides information about the system's connection in terms of general connection type (e.g., 'wifi', 'cellular', etc.). This can be used to select high definition content or low definition content based on the user's connection. The entire API consists of the addition of the NetworkInformation interface and a single property to the Navigator interface: Navigator.connection.

Demo
​

source

isSupported: true
isOnline: true
saveData: false
onlineAt: 1701206216470
downlink: 10
effectiveType: '4g'
rtt: 0

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

const { isOnline, offlineAt, downlink, downlinkMax, effectiveType, saveData, type } = useNetwork()

console.log(isOnline.value)

To use as an object, wrap it with reactive()

js
import { reactive } from 'vue'

const network = reactive(useNetwork())

console.log(network.isOnline)
Component Usage
​

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

html
<UseNetwork v-slot="{ isOnline, type }">
  Is Online: {{ isOnline }}
  Type: {{ type }}
</UseNetwork>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
丶远方
vaakian X
Kirk Lin
Lexpeartha
webfansplz
wheat
Alex Kozack
Antério Vieira
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)
useMouse | VueUse

useMouse
​
Category
Sensors
Export Size
825 B
Last Changed
2 months ago

Reactive mouse position

Demo
​

source

Basic Usage

x: 0
y: 0
sourceType: null


Extractor Usage

x: 0
y: 0
sourceType: null

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

const { x, y, sourceType } = useMouse()

Touch is enabled by default. To only detect mouse changes, set touch to false. The dragover event is used to track mouse position while dragging.

js
const { x, y } = useMouse({ touch: false })
Custom Extractor
​

It's also possible to provide a custom extractor function to get the position from the event.

TypeScript
ts
import type { UseMouseEventExtractor } from '@vueuse/core'
import { useMouse, useParentElement } from '@vueuse/core'
const parentEl = useParentElement()
const extractor: UseMouseEventExtractor = (event) =>
  event instanceof Touch ? null : [event.offsetX, event.offsetY]
const { x, y, sourceType } = useMouse({ target: parentEl, type: extractor })
Component Usage
​

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

html
<UseMouse v-slot="{ x, y }">
  x: {{ x }}
  y: {{ y }}
</UseMouse>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
karukenert
Cats Juice
丶远方
RAX7
François Lévesque
vaakian X
Sergey Danilchenko
lzdFeiFei
Scott Bedard
Marshall Thompson
Shinigami
wheat
Alex Kozack
Antério Vieira
Changelog
​
v10.4.0 on 8/25/2023
c2f64 - fix: position won't be changed on page scroll when type is page, closes #2922 (#3244)
v10.1.0 on 4/22/2023
4bb5b - feat: support custom event extractor (#2991)
v10.0.0-beta.4 on 4/13/2023
39d18 - feat: support type: screen (#2467)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.10.0 on 1/3/2023
0c39d - feat: support for movement detection (#2589)
v8.9.3 on 7/14/2022
4d2c8 - fix!: rename type MouseOptions to UseMouseOptions (#1877)
useKeyModifier | VueUse

useKeyModifier
​
Category
Sensors
Export Size
587 B
Last Changed
last year

Reactive Modifier State. Tracks state of any of the supported modifiers - see Browser Compatibility notes.

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

source

capsLock
numLock
scrollLock
shift
control
alt
Usage
​
ts
import { useKeyModifier } from '@vueuse/core'

const capsLockState = useKeyModifier('CapsLock')

console.log(capsLockState.value)
Events
​

You can customize which events will prompt the state to update. By default, these are mouseup, mousedown, keyup, keydown. To customize these events:

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

const capsLockState = useKeyModifier('CapsLock', { events: ['mouseup', 'mousedown'] })

console.log(capsLockState) // null

// Caps Lock turned on with key press
console.log(capsLockState) // null

// Mouse button clicked
console.log(capsLockState) // true
Initial State
​

By default, the returned ref will be Ref<null> until the first event is received. You can explicitly pass the initial state to it via:

ts
const capsLockState1 = useKeyModifier('CapsLock') // Ref<boolean | null>
const capsLockState2 = useKeyModifier('CapsLock', { initial: false }) // Ref<boolean>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
Joe Maylor
Changelog
​
v8.9.3 on 7/14/2022
584a0 - fix!: rename type ModifierOptions to UseModifierOptions (#1871)
useInfiniteScroll | VueUse

useInfiniteScroll
​
Category
Sensors
Export Size
1.98 kB
Last Changed
3 months ago

Infinite scrolling of the element.

Demo
​

source

1
2
3
4
5
6
Usage
​
html
<script setup lang="ts">
import { ref } from 'vue'
import { useInfiniteScroll } from '@vueuse/core'

const el = ref<HTMLElement | null>(null)
const data = ref([1, 2, 3, 4, 5, 6])

useInfiniteScroll(
  el,
  () => {
    // load more
    data.value.push(...moreData)
  },
  { distance: 10 }
)
</script>

<template>
  <div ref="el">
    <div v-for="item in data">
      {{ item }}
    </div>
  </div>
</template>
Directive Usage
​

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

html
<script setup lang="ts">
import { ref } from 'vue'
import { vInfiniteScroll } from '@vueuse/components'

const data = ref([1, 2, 3, 4, 5, 6])

function onLoadMore() {
  const length = data.value.length + 1
  data.value.push(...Array.from({ length: 5 }, (_, i) => length + i))
}
</script>

<template>
  <div v-infinite-scroll="onLoadMore">
    <div v-for="item in data" :key="item">
      {{ item }}
    </div>
  </div>

  <!-- with options -->
  <div v-infinite-scroll="[onLoadMore, { 'distance' : 10 }]">
    <div v-for="item in data" :key="item">
      {{ item }}
    </div>
  </div>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
webfansplz
Toni Engelhardt
erikwu
wonderl17
Scott Bedard
Sarwan Nizamani
Hawtim
sand4rt
Enzo Innocenzi
wheat
Melih Altıntaş
Changelog
​
v10.3.0 on 7/30/2023
5ce61 - fix: improve visibility check (#3212)
v10.2.1 on 6/28/2023
a4dfa - fix: prevent infinite load when v-show set false (#3143)
v10.1.1 on 5/2/2023
a88fe - fix: re-measure arrived states when async infinite scroll resolves (#3030)
v10.0.0-beta.5 on 4/13/2023
d3a2b - fix!: improve loading strategies, close #1701, close #1685
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.4 on 7/17/2022
6c8fb - fix: add direction types (#1929)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
v8.6.0 on 5/31/2022
5a1b9 - feat: new options (#1354)
useFocus | VueUse

useFocus
​
Category
Sensors
Export Size
605 B
Last Changed
4 months ago

Reactive utility to track or set the focus state of a DOM element. State changes to reflect whether the target element is the focused element. Setting reactive value from the outside will trigger focus and blur events for true and false values respectively.

Demo
​

source

Paragraph that can be focused

Button that can be focused
The input control has focus
Focus textFocus inputFocus button
Basic Usage
​
ts
import { useFocus } from '@vueuse/core'

const target = ref()
const { focused } = useFocus(target)

watch(focused, (focused) => {
  if (focused)
    console.log('input element has been focused')
  else console.log('input element has lost focus')
})
Setting initial focus
​

To focus the element on its first render one can provide the initialValue option as true. This will trigger a focus event on the target element.

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

const target = ref()
const { focused } = useFocus(target, { initialValue: true })
Change focus state
​

Changes of the focused reactive ref will automatically trigger focus and blur events for true and false values respectively. You can utilize this behavior to focus the target element as a result of another action (e.g. when a button click as shown below).

html
<template>
  <div>
    <button type="button" @click="focused = true">Click me to focus input below</button>
    <input ref="input" type="text">
  </div>
</template>

<script>
import { ref } from 'vue'
import { useFocus } from '@vueuse/core'

export default {
  setup() {
    const input = ref()
    const { focused } = useFocus(input)

    return {
      input,
      focused,
    }
  }
}
</script>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
William T. Kirby
Max
Waleed Khaled
Jelf
ByMykel
Levi Bucsis
webfansplz
Jakub Freisler
Changelog
​
v10.3.0 on 7/30/2023
80329 - feat: support :focus-visible (#3254)
v9.13.0 on 2/18/2023
7cd88 - fix: listen focus and blur to the targetElement (#2631)
useIdle | VueUse

useIdle
​
Category
Sensors
Export Size
977 B
Last Changed
8 months ago

Tracks whether the user is being inactive.

Demo
​

source

For demonstration purpose, the idle timeout is set to 5s in this demo (default 1min).
Idle: false
Inactive: 0s
Usage
​
js
import { useIdle } from '@vueuse/core'

const { idle, lastActive } = useIdle(5 * 60 * 1000) // 5 min

console.log(idle.value) // true or false

Programatically resetting:

js
import { watch } from 'vue'
import { useCounter, useIdle } from '@vueuse/core'

const { inc, count } = useCounter()

const { idle, lastActive, reset } = useIdle(5 * 60 * 1000) // 5 min

watch(idle, (idleValue) => {
  if (idleValue) {
    inc()
    console.log(`Triggered ${count.value} times`)
    reset() // restarts the idle timer. Does not change lastActive value
  }
})
Component Usage
​

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

html
<UseIdle v-slot="{ idle }" :timeout="5 * 60 * 1000">
  Is Idle: {{ idle }}
</UseIdle>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
wheat
Intaek H
nahvego
Hawtim
vaakian X
Jelf
Dan Mindru
btea
Shinigami
Alex Kozack
Antério Vieira
Changelog
​
v10.0.0-beta.1 on 3/23/2023
f4d35 - feat: add reset capability (#2880)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v8.9.3 on 7/14/2022
4ff55 - fix!: rename type IdleOptions to UseIdleOptions (#1869)
useGeolocation | VueUse

useGeolocation
​
Category
Sensors
Export Size
526 B
Last Changed
4 months ago

Reactive Geolocation API. It allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

Demo
​

source

{
  "coords": {
    "accuracy": 0,
    "latitude": null,
    "longitude": null,
    "altitude": null,
    "altitudeAccuracy": null,
    "heading": null,
    "speed": null
  },
  "locatedAt": null,
  "error": "User denied Geolocation"
}
Pause watchStart watch
Usage
​
js
import { useGeolocation } from '@vueuse/core'

const { coords, locatedAt, error, resume, pause } = useGeolocation()
State	Type	Description
coords	Coordinates	information about the position retrieved like the latitude and longitude
locatedAt	Date	The time of the last geolocation call
error	string	An error message in case geolocation API fails.
resume	function	Control function to resume updating geolocation
pause	function	Control function to pause updating geolocation
Config
​

useGeolocation function takes PositionOptions object as an optional parameter.

Component Usage
​

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

html
<UseGeolocation v-slot="{ coords: { latitude, longitude } }">
  Latitude: {{ latitude }}
  Longitude: {{ longitude }}
</UseGeolocation>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Antério Vieira
Jelf
丶远方
vaakian X
Enric Bisbe Gil
Egor Startsev
Michael J. Roberts
Shinigami
wheat
Alex Kozack
Sanxiaozhizi
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.7.0 on 12/16/2022
161fd - fix: Implement immediate option (#2472)
v9.5.0 on 11/9/2022
2c4fd - feat: pause and resume controls (#2376)
v8.9.3 on 7/14/2022
48f79 - fix!: rename type GeolocationOptions to UseGeolocationOptions (#1868)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
useFps | VueUse

useFps
​
Category
Sensors
Export Size
458 B
Last Changed
2 years ago

Reactive FPS (frames per second).

Demo
​

source

FPS: 37
Usage
​
js
import { useFps } from '@vueuse/core'

const fps = useFps()
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
webfansplz
jelf
Changelog
​
No recent changes
useFocusWithin | VueUse

useFocusWithin
​
Category
Sensors
Export Size
769 B
Last Changed
8 months ago

Reactive utility to track if an element or one of its decendants has focus. It is meant to match the behavior of the :focus-within CSS pseudo-class. A common use case would be on a form element to see if any of its inputs currently have focus.

Demo
​

source

Focus in form: false
Basic Usage
​
html
<template>
  <form ref="target">
    <input type="text" placeholder="First Name">
    <input type="text" placeholder="Last Name">
    <input type="text" placeholder="Email">
    <input type="text" placeholder="Password">
  </form>
</template>

<script>
import { useFocusWithin } from '@vueuse/core'

const target = ref();
const { focused } = useFocusWithin(target)

watch(focused, focused => {
  if (focused) console.log('Target contains the focused element')
  else console.log('Target does NOT contain the focused element')
})
</script>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
sun0day
Mikhailov Nikita
Boris Moiseev
Jelf
William T. Kirby
Changelog
​
v10.0.0-beta.3 on 4/13/2023
e75a5 - feat: update deps
v9.2.0 on 9/5/2022
3316e - fix: change focused typing to ComputedRef (#2073)
v8.9.3 on 7/14/2022
1b871 - fix!: rename type FocusWithinReturn to UseFocusWithinReturn (#1866)
useElementHover | VueUse

useElementHover
​
Category
Sensors
Export Size
598 B
Last Changed
8 months ago

Reactive element's hover state.

Demo
​

source

Hover me
Usage
​
vue
<script setup>
import { useElementHover } from '@vueuse/core'

const myHoverableElement = ref()
const isHovered = useElementHover(myHoverableElement)
</script>

<template>
  <button ref="myHoverableElement">
    {{ isHovered }}
  </button>
</template>
Directive Usage
​

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

html
<script setup lang="ts">
import { ref } from 'vue'
import { vElementHover } from '@vueuse/components'

const isHovered = ref(false)
function onHover(state: boolean) {
  isHovered.value = state
}
</script>

<template>
  <button v-element-hover="onHover">
    {{ isHovered ? 'Thank you!' : 'Hover me' }}
  </button>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
webfansplz
Jelf
geekreal
cx33
Joe Maylor
Changelog
​
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
v10.0.0-beta.0 on 3/14/2023
c86f2 - fix: window is not defined (#2793)
v9.13.0 on 2/18/2023
23283 - feat: give hook delay properties (#2741)
v9.1.1 on 8/23/2022
d9c0c - fix: support set el ref type (#2079)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useElementByPoint | VueUse

useElementByPoint
​
Category
Sensors
Export Size
953 B
Last Changed
3 weeks ago

Reactive element by point.

Demo
​

source

X
Y
Usage
​
ts
import { useElementByPoint, useMouse } from '@vueuse/core'

const { x, y } = useMouse({ type: 'client' })
const { element } = useElementByPoint({ x, y })
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
wheat
vaakian X
BaboonKing
Changelog
​
v10.2.0 on 6/16/2023
31b66 - feat: new multiple and interval options (#3089)
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
c3639 - fix: make document configurable (#2614)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useDisplayMedia | VueUse

useDisplayMedia
​
Category
Sensors
Export Size
476 B
Last Changed
2 months ago
Related
useUserMedia

Reactive mediaDevices.getDisplayMedia streaming.

Demo
​

source

Start sharing my screen
Usage
​
ts
import { useDisplayMedia } from '@vueuse/core'

const { stream, start } = useDisplayMedia()

// start streaming

start()
ts
const video = document.getElementById('video')

watchEffect(() => {
  // preview on a video element
  video.srcObject = stream.value
})
Source
​

Source • Demo • Docs

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

useDevicesList
​
Category
Sensors
Export Size
1.09 kB
Last Changed
8 months ago
Related
useUserMedia

Reactive enumerateDevices listing available input/output devices.

Demo
​

source

CAMERA (0)
MICROPHONES (0)
SPEAKERS (0)
Usage
​
js
import { useDevicesList } from '@vueuse/core'

const {
  devices,
  videoInputs: cameras,
  audioInputs: microphones,
  audioOutputs: speakers,
} = useDevicesList()
Component
​
html
<UseDevicesList v-slot="{ videoInputs, audioInputs, audioOutputs }">
  Cameras: {{ videoInputs }}
  Microphones: {{ audioInputs }}
  Speakers: {{ audioOutputs }}
</UseDevicesList>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
wheat
Félix Zapata
vaakian X
vaakian X
Jelf
Andras Serfozo
Alex Kozack
Changelog
​
v10.0.0-beta.2 on 3/28/2023
0823d - fix: show devices for Firefox (#2798)
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)
useDeviceOrientation | VueUse

useDeviceOrientation
​
Category
Sensors
Export Size
672 B
Last Changed
last year

Reactive DeviceOrientationEvent. Provide web developers with information from the physical orientation of the device running the web page.

Demo
​

source

isSupported: true
isAbsolute: false
alpha: null
beta: null
gamma: null

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

const {
  isAbsolute,
  alpha,
  beta,
  gamma,
} = useDeviceOrientation()
State	Type	Description
isAbsolute	boolean	A boolean that indicates whether or not the device is providing orientation data absolutely.
alpha	number	A number representing the motion of the device around the z axis, express in degrees with values ranging from 0 to 360.
beta	number	A number representing the motion of the device around the x axis, express in degrees with values ranging from -180 to 180.
gamma	number	A number representing the motion of the device around the y axis, express in degrees with values ranging from -90 to 90.

You can find more information about the state on the MDN.

Component Usage
​

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

html
<UseDeviceOrientation v-slot="{ alpha, beta, gamma }">
  Alpha: {{ alpha }}
  Beta: {{ beta }}
  Gamma: {{ gamma }}
</UseDeviceOrientation>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Antério Vieira
vaakian X
Jelf
Shinigami
wheat
Alex Kozack
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)
useDeviceMotion | VueUse

useDeviceMotion
​
Category
Sensors
Export Size
703 B
Last Changed
2 years ago

Reactive DeviceMotionEvent. Provide web developers with information about the speed of changes for the device's position and orientation.

Demo
​

source

Device Motion:
{
  "acceleration": {},
  "accelerationIncludingGravity": {},
  "rotationRate": {},
  "interval": 16
}
Usage
​
js
import { useDeviceMotion } from '@vueuse/core'

const {
  acceleration,
  accelerationIncludingGravity,
  rotationRate,
  interval,
} = useDeviceMotion()
State	Type	Description
acceleration	object	An object giving the acceleration of the device on the three axis X, Y and Z.
accelerationIncludingGravity	object	An object giving the acceleration of the device on the three axis X, Y and Z with the effect of gravity.
rotationRate	object	An object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma.
interval	Number	A number representing the interval of time, in milliseconds, at which data is obtained from the device..

You can find more information about the state on the MDN.

Component Usage
​

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

html
<UseDeviceMotion v-slot="{ acceleration }">
  Acceleration: {{ acceleration }}
</UseDeviceMotion>
Source
​

Source • Demo • Docs

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

useBattery
​
Category
Sensors
Export Size
743 B
Last Changed
2 months ago

Reactive Battery Status API, more often referred to as the Battery API, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. This can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss.

Demo
​

source

isSupported: true
charging: true
chargingTime: 3000
dischargingTime: 0
level: 0.84

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

const { charging, chargingTime, dischargingTime, level } = useBattery()
State	Type	Description
charging	Boolean	If the device is currently charging.
chargingTime	Number	The number of seconds until the device becomes fully charged.
dischargingTime	Number	The number of seconds before the device becomes fully discharged.
level	Number	A number between 0 and 1 representing the current charge level.
Use-cases
​

Our applications normally are not empathetic to battery level, we can make a few adjustments to our applications that will be more friendly to low battery users.

Trigger a special "dark-mode" battery saver theme settings.
Stop auto playing videos in news feeds.
Disable some background workers that are not critical.
Limit network calls and reduce CPU/Memory consumption.
Component Usage
​

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

html
<UseBattery v-slot="{ charging }">
  Is Charging: {{ charging }}
</UseBattery>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
丶远方
vaakian X
Jelf
Piet Althoff
Shinigami
wheat
Alex Kozack
Antério Vieira
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)
onLongPress | VueUse

onLongPress
​
Category
Sensors
Export Size
675 B
Last Changed
3 weeks ago

Listen for a long press on an element.

Function provides modifiers in options

stop
once
prevent
capture
self
Demo
​

source

Long Pressed: false

Press long (500ms)Press long (1000ms)Reset
Usage
​
html
<script setup lang="ts">
import { ref } from 'vue'
import { onLongPress } from '@vueuse/core'

const htmlRefHook = ref<HTMLElement | null>(null)
const longPressedHook = ref(false)

const onLongPressCallbackHook = (e: PointerEvent) => {
  longPressedHook.value = true
}
const resetHook = () => {
  longPressedHook.value = false
}

onLongPress(
  htmlRefHook,
  onLongPressCallbackHook,
  { modifiers: { prevent: true } }
)
</script>

<template>
  <p>Long Pressed: {{ longPressedHook }}</p>

  <button ref="htmlRefHook" class="ml-2 button small">
    Press long
  </button>

  <button class="ml-2 button small" @click="resetHook">
    Reset
  </button>
</template>
Component Usage
​

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

html
<script setup lang="ts">
import { ref } from 'vue'
import { OnLongPress } from '@vueuse/components'

const longPressedComponent = ref(false)

const onLongPressCallbackComponent = (e: PointerEvent) => {
  longPressedComponent.value = true
}
const resetComponent = () => {
  longPressedComponent.value = false
}
</script>

<template>
  <p>Long Pressed: {{ longPressedComponent }}</p>

  <OnLongPress
    as="button"
    class="ml-2 button small"
    @trigger="onLongPressCallbackComponent"
  >
    Press long
  </OnLongPress>

  <button class="ml-2 button small" @click="resetComponent">
    Reset
  </button>
</template>
Directive Usage
​

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

html
<script setup lang="ts">
import { ref } from 'vue'
import { vOnLongPress } from '@vueuse/components'

const longPressedDirective = ref(false)

const onLongPressCallbackDirective = (e: PointerEvent) => {
  longPressedDirective.value = true
}
const resetDirective = () => {
  longPressedDirective.value = false
}
</script>

<template>
  <p>Long Pressed: {{ longPressedDirective }}</p>

  <button v-on-long-press.prevent="onLongPressCallbackDirective" class="ml-2 button small">
    Press long
  </button>

  <button
    v-on-long-press="[onLongPressCallbackDirective, {delay: 1000, modifiers: { stop: true }}]"
    class="ml-2button small"
  >
    Press long (with options)
  </button>

  <button class="ml-2 button small" @click="resetDirective">
    Reset
  </button>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
webfansplz
Lee Crosby
丶远方
vaakian X
sun0day
Yugang Cao
Mikhailov Nikita
三咲智子
wheat
AllenYu
余小磊
Changelog
​
v10.6.0 on 11/9/2023
8eb0b - feat(onLongClick): return stop function (#3506)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v8.8.0 on 7/6/2022
f0472 - feat: added modifiers (#1719)
onKeyStroke | VueUse

onKeyStroke
​
Category
Sensors
Export Size
651 B
Last Changed
3 weeks ago

Listen for keyboard keystrokes.

Demo
​

source

Use the arrow keys or w a s d keys to control the movement of the ball.

Repeated events are ignored on the key `d` or `->`.

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

onKeyStroke('ArrowDown', (e) => {
  e.preventDefault()
})

See this table for all key codes.

Listen To Multiple Keys
​
js
import { onKeyStroke } from '@vueuse/core'

onKeyStroke(['s', 'S', 'ArrowDown'], (e) => {
  e.preventDefault()
})

// listen to all keys by [true / skip the keyDefine]
onKeyStroke(true, (e) => {
  e.preventDefault()
})
onKeyStroke((e) => {
  e.preventDefault()
})
Custom Event Target
​
js
onKeyStroke('A', (e) => {
  console.log('Key A pressed on document')
}, { target: document })
Ignore Repeated Events
​

The callback will trigger only once when pressing A and hold down.

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

// use `autoRepeat` option
onKeyStroke('A', (e) => {
  console.log('Key A pressed')
}, { dedupe: true })

Reference: KeyboardEvent.repeat

Directive Usage
​

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

html
<script setup lang="ts">
import { vOnKeyStroke } from '@vueuse/components'
function onUpdate(e: KeyboardEvent) {
  // impl...
}
</script>

<template>
  <input v-on-key-stroke:c,v="onUpdate" type="text">
  <!-- with options -->
  <input v-on-key-stroke:c,v="[onUpdate, { eventName: 'keyup' }]" type="text">
</template>
Custom Keyboard Event
​
js
onKeyStroke('Shift', (e) => {
  console.log('Shift key up')
}, { eventName: 'keyup' })

Or

js
onKeyUp('Shift', () => console.log('Shift key up'))
Shorthands
​
onKeyDown - alias for onKeyStroke(key, handler, {eventName: 'keydown'})
onKeyPressed - alias for onKeyStroke(key, handler, {eventName: 'keypress'})
onKeyUp - alias for onKeyStroke(key, handler, {eventName: 'keyup'})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
webfansplz
Anonimus Programus
yn
David Hewson
lainbo
jack zhang
vaakian X
vaakian X
azaleta
Curt Grimes
Jelf
leovoon
Arpit
Ivan Que
Alex Kozack
yang
Changelog
​
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.2 on 3/28/2023
22ca5 - feat: support ignoring repeated stroke (#2652)
v9.10.0 on 1/3/2023
28614 - fix: make target ref nullable (#2579)
v9.3.0 on 9/26/2022
86c12 - feat: support capture all handler (#2197)
v8.9.2 on 7/12/2022
57ed5 - fix!: rename type KeyStrokeOptions to OnKeyStrokeOptions (#1807)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)