matijao/webdev huggingface dataset:
useUrlSearchParams | VueUse

useUrlSearchParams
​
Category
Browser
Export Size
1.59 kB
Last Changed
last year

Reactive URLSearchParams

Demo
​

source

foo=bar
vueuse=awesome
Usage
​
js
import { useUrlSearchParams } from '@vueuse/core'

const params = useUrlSearchParams('history')

console.log(params.foo) // 'bar'

params.foo = 'bar'
params.vueuse = 'awesome'
// url updated to `?foo=bar&vueuse=awesome`
Hash Mode
​

When using with hash mode route, specify the mode to hash

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

const params = useUrlSearchParams('hash')

params.foo = 'bar'
params.vueuse = 'awesome'
// url updated to `#/your/route?foo=bar&vueuse=awesome`
Hash Params
​

When using with history mode route, but want to use hash as params, specify the mode to hash-params

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

const params = useUrlSearchParams('hash-params')

params.foo = 'bar'
params.vueuse = 'awesome'
// url updated to `/your/route#foo=bar&vueuse=awesome`
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
lstoeferle
sun0day
专业逮虾户aa
Marius
Patrick Stillhart
odex21
Michel EDIGHOFFER
Alex Kozack
Changelog
​
v9.2.0 on 9/5/2022
7b288 - feat: add write option (#2165)
v9.1.1 on 8/23/2022
42300 - fix(useURLSearchParams): avoid referencing to global location (#2066)
v8.7.0 on 6/16/2022
1ef51 - fix: preserve history state when updating query (#1661)
useCloned | VueUse

useCloned
​
Category
Utilities
Export Size
499 B
Last Changed
6 months ago

Reactive clone of a ref. By default, it use JSON.parse(JSON.stringify()) to do the clone.

Demo
​

source

reset
Usage
​
ts
import { useCloned } from '@vueuse/core'

const original = ref({ key: 'value' })

const { cloned } = useCloned(original)

original.value.key = 'some new value'

console.log(cloned.value.key) // 'some new value'
Manual cloning
​
ts
import { useCloned } from '@vueuse/core'

const original = ref({ key: 'value' })

const { cloned, sync } = useCloned(original, { manual: true })

original.value.key = 'manual'

console.log(cloned.value.key) // 'value'

sync()

console.log(cloned.value.key)// 'manual'
Custom Clone Function
​

Using klona for example:

ts
import { useCloned } from '@vueuse/core'
import { klona } from 'klona'

const original = ref({ key: 'value' })

const { cloned, sync } = useCloned(original, { clone: klona })
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jeff Yang (楊德誠)
Akkapon Chainarong
Eduardo Wesley
Mikhailov Nikita
Changelog
​
v10.2.0 on 6/16/2023
6d630 - fix: check for getter function to watch (#3142)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
v9.2.0 on 9/5/2022
369e1 - feat(useVModel): support clone option (#2022)
0a0a1 - feat: new function (#2045)
useTimestamp | VueUse

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

Reactive current timestamp

Demo
​

source

Timestamp: 1701206238338
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)
templateRef | VueUse

templateRef
​
Category
Component
Export Size
270 B
Last Changed
last year

Shorthand for binding ref to template element.

Usage
​
vue
<script lang="ts">
import { templateRef } from '@vueuse/core'

export default {
  setup() {
    const target = templateRef('target')

    // no need to return the `target`, it will bind to the ref magically
  },
}
</script>

<template>
  <div ref="target" />
</template>
With JSX/TSX
​
tsx
import { templateRef } from '@vueuse/core'

export default {
  setup() {
    const target = templateRef<HTMLElement | null>('target', null)

    // use string ref
    return () => <div ref="target"></div>
  },
}
<script setup>
​

There is no need for this when using with <script setup> since all the variables will be exposed to the template. It will be exactly the same as ref.

vue
<script setup lang="ts">
import { ref } from 'vue'

const target = ref<HTMLElement | null>(null)
</script>

<template>
  <div ref="target" />
</template>
Source
​

Source • Docs

Contributors
​
Anthony Fu
Hollis Wu
likeswinds
Alex Kozack
zhong666
Changelog
​
v9.3.0 on 9/26/2022
cd798 - fix: add Component type (#2203)
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: 8
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)
useSpeechSynthesis | VueUse

useSpeechSynthesis
​
Category
Sensors
Export Size
724 B
Last Changed
2 months ago

Reactive SpeechSynthesis.

Can I use?

Demo
​

source

Spoken Text
Language
Select Language


Pitch


Rate
SpeakPauseStop
Usage
​
ts
import { useSpeechSynthesis } from '@vueuse/core'

const {
  isSupported,
  isPlaying,
  status,
  voiceInfo,
  utterance,
  error,
  stop,

  toggle,
  speak,
} = useSpeechSynthesis()
Options
​

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

ts
useSpeechSynthesis({
  lang: 'en-US',
  pitch: 1,
  rate: 1,
  volume: 1,
})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
sibbng
Jelf
wheat
Kirill Shestmintsev
糠帅傅
zwkkwz1
云游君
Changelog
​
v10.3.0 on 7/30/2023
ac88f - feat: add reactivity for pitch and rate (#3205)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef
v9.13.0 on 2/18/2023
820e2 - feat: add stop function (#2774)
v9.0.0-beta.1 on 7/20/2022
a524b - fix: remove duplicated onend, fix demo (#1941)
v9.0.0-beta.0 on 7/17/2022
db61f - fix: rename type Status to UseSpeechSynthesisStatus
v8.9.3 on 7/14/2022
011af - refactor!: remove voiceInfo, allow voice as ref (#1882)
42516 - fix!: rename type SpeechSynthesisOptions to UseSpeechSynthesisOptions (#1890)
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)
useDevicePixelRatio | VueUse

useDevicePixelRatio
​
Category
Sensors
Export Size
294 B
Last Changed
2 months ago

Reactively track window.devicePixelRatio

NOTE: there is no event listener for window.devicePixelRatio change. So this function uses Testing media queries programmatically (window.matchMedia) applying the same mechanism as described in this example.

Demo
​

source

Device Pixel Ratio:
pixelRatio: 1

Zoom in and out (or move the window to a screen with a different scaling factor) to see the value changes
Usage
​
js
import { useDevicePixelRatio } from '@vueuse/core'

export default {
  setup() {
    const { pixelRatio } = useDevicePixelRatio()

    return { pixelRatio }
  },
}
Component Usage
​

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

html
<UseDevicePixelRatio v-slot="{ pixelRatio }">
  Pixel Ratio: {{ pixelRatio }}
</UseDevicePixelRatio>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Antério Vieira
Waleed Khaled
wheat
vaakian X
Shinigami
Alex Kozack
Konstantin Barabanov
Changelog
​
v9.13.0 on 2/18/2023
83feb - fix: remove unnecessary cleanup (#2325)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.2.0 on 9/5/2022
eb054 - fix: more efficient mechanism (#2044)
onStartTyping | VueUse

onStartTyping
​
Category
Sensors
Export Size
704 B
Last Changed
8 months ago

Fires when users start typing on non-editable elements.

Demo
​

source

Type anything
Usage
​
html
<input ref="input" type="text" placeholder="Start typing to focus" />
ts
import { onStartTyping } from '@vueuse/core'

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

    onStartTyping(() => {
      if (!input.value.active)
        input.value.focus()
    })

    return {
      input,
    }
  },
}
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
meenie-net
丶远方
Alex Kozack
Nurettin Kaya
Antério Vieira
Seifeldin Mahjoub
Changelog
​
v10.0.0-beta.3 on 4/13/2023
e9ab3 - fix: fix char ascii (#2932)
useFileSystemAccess | VueUse

useFileSystemAccess
​
Category
Browser
Export Size
878 B
Last Changed
2 months ago

Create and read and write local files with FileSystemAccessAPI

Demo
​

source

Open
New file
Save
Save as
DataType
Text
ArrayBuffer
Blob
isSupported: true
fileName: ''
fileMIME: ''
fileSize: 0
fileLastModified: 0

Usage
​
ts
import { useFileSystemAccess } from '@vueuse/core'

const { isSupported, data, file, fileName, fileMIME, fileSize, fileLastModified, create, open, save, saveAs, updateData } = useFileSystemAccess()
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelf
171H
Carlos Gamez
wheat
Changelog
​
v10.4.0 on 8/25/2023
a9c8b - fix: make options to be optional (#3320)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
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)
useMouseInElement | VueUse

useMouseInElement
​
Category
Elements
Export Size
1.12 kB
Last Changed
3 weeks ago

Reactive mouse position related to an element

Demo
​

source

Hover me
x: 0
y: 0
sourceType: null
elementX: -976
elementY: -408
elementPositionX: 976
elementPositionY: 408
elementHeight: 160
elementWidth: 160
isOutside: true

Usage
​
html
<template>
  <div ref="target">
    <h1>Hello world</h1>
  </div>
</template>

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

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

    const { x, y, isOutside } = useMouseInElement(target)

    return { x, y, isOutside }
  }
}
</script>
Component Usage
​

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

html
<UseMouseInElement v-slot="{ elementX, elementY, isOutside }">
  x: {{ elementX }}
  y: {{ elementY }}
  Is Outside: {{ isOutside }}
</UseMouseInElement>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
wheat
Aymoc
Mikhailov Nikita
vaakian X
Jelf
Ivan Agafonov
Shinigami
Alex Kozack
ctholho
Nurettin Kaya
Antério Vieira
Changelog
​
v10.6.0 on 11/9/2023
7c88d - fix: optimize outside computation (#3380)
v9.12.0 on 1/29/2023
54f4e - fix: check if mouse out of window (#2458)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v8.9.3 on 7/14/2022
4d2c8 - fix(useMouse)!: rename type MouseOptions to UseMouseOptions (#1877)
v8.6.0 on 5/31/2022
ebd60 - fix isOutside is true for detached elements (#1614) (#1615)
useElementVisibility | VueUse

useElementVisibility
​
Category
Elements
Export Size
692 B
Last Changed
2 months ago

Tracks the visibility of an element within the viewport.

Demo
​

source

Info on the right bottom corner
Target Element (scroll down)
Element inside the viewport
Usage
​
html
<template>
  <div ref="target">
    <h1>Hello world</h1>
  </div>
</template>

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

export default {
  setup() {
    const target = ref(null)
    const targetIsVisible = useElementVisibility(target)

    return {
      target,
      targetIsVisible,
    }
  }
}
</script>
Component Usage
​

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

html
<UseElementVisibility v-slot="{ isVisible }">
  Is Visible: {{ isVisible }}
</UseElementVisibility>
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 { vElementVisibility } from '@vueuse/components'

const target = ref(null)
const isVisible = ref(false)

function onElementVisibility(state) {
  isVisible.value = state
}
</script>

<template>
  <div v-element-visibility="onElementVisibility">
    {{ isVisible ? 'inside' : 'outside' }}
  </div>

  <!-- with options -->
  <div ref="target">
    <div v-element-visibility="[onElementVisibility, { scrollTarget: target }]">
      {{ isVisible ? 'inside' : 'outside' }}
    </div>
  </div>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Scott Bedard
wheat
Amr Bashir
erikwu
Curt Grimes
vaakian X
sun0day
三咲智子
Jelf
webfansplz
AllenYu
Ary Raditya
Chung, Lian
Carlos Yanes
Alex Kozack
Changelog
​
v10.4.0 on 8/25/2023
429ed - fix: adjust threshold to 0 to fix visibility issue with large element (#3308)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
v10.0.0-beta.2 on 3/28/2023
74b00 - fix!: use useIntersectionObserver instead of scroll event handler (#2551)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.2.0 on 9/5/2022
de5a9 - feat: support watch the real element (#2169)
v8.9.3 on 7/14/2022
86df7 - fix!: rename type VisibilityScrollTargetOptions to UseElementVisibilityOptions (#1863)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useTimeoutPoll | VueUse

useTimeoutPoll
​
Category
Utilities
Export Size
407 B
Last Changed
5 months ago

Use timeout to poll something. It's will trigger callback after last task is done.

Demo
​

source

Count: 0
isActive: false
pauseresume
Usage
​
ts
import { useTimeoutPoll } from '@vueuse/core'

const count = ref(0)

async function fetchData() {
  await new Promise(resolve => setTimeout(resolve, 1000))
  count.value++
}

// Only trigger after last fetch is done
const { isActive, pause, resume } = useTimeoutPoll(fetchData, 1000)
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
David Vallejo
jiadesen
sun0day
Jelf
Wenlu Wang
Changelog
​
v10.2.1 on 6/28/2023
7a897 - fix: unexpected immediate execution (#3159)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
v9.0.0-beta.1 on 7/20/2022
4ca70 - fix(useTimeoutFn,useTimeout)!: rename type TimeoutOptions to UseTimeoutOptions and TimeoutFnOptions to UseTimeoutFnOptions (#1944)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useSupported | VueUse

useSupported
​
Category
Utilities
Export Size
194 B
Last Changed
8 months ago

SSR compatibility isSupported

Usage
​
ts
import { useSupported } from '@vueuse/core'

const isSupported = useSupported(() => navigator && 'getBattery' in navigator)

if (isSupported.value) {
  // do something
  navigator.getBattery
}
Source
​

Source • Docs

Contributors
​
Fernando Fernández
Jelf
Changelog
​
v10.0.0-beta.2 on 3/28/2023
55a32 - feat: support tracking reactivity for the callback function (#2904)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
useDebouncedRefHistory | VueUse

useDebouncedRefHistory
​
Category
State
Export Size
1.7 kB
Last Changed
8 months ago
Related
useRefHistory
useThrottledRefHistory

Shorthand for useRefHistory with debounced filter.

Demo
​

source

Count: 0
IncrementDecrement/UndoRedo
Delay (in ms):



History (limited to 10 records for demo)
2023-11-28 22:17:15{ value: 0 }
Usage
​

This function takes a snapshot of your counter after 1000ms when the value of it starts to change.

ts
import { ref } from 'vue'
import { useDebouncedRefHistory } from '@vueuse/core'

const counter = ref(0)
const { history, undo, redo } = useDebouncedRefHistory(counter, { deep: true, debounce: 1000 })
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Roman Harmyder
wheat
Changelog
​
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useSessionStorage | VueUse

useSessionStorage
​
Category
State
Export Size
2.03 kB
Last Changed
8 months ago
Related
useStorage

Reactive SessionStorage.

Usage
​

Please refer to useStorage

Source
​

Source • Docs

Contributors
​
Anthony Fu
Antério Vieira
ntnyq
Jelf
Shinigami
Pig Fang
Alex Kozack
Changelog
​
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
v8.9.3 on 7/14/2022
499f6 - fix(useStorage)!: rename type StorageOptions to UseStorageOptions (#1867)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useStepper | VueUse

useStepper
​
Category
Utilities
Export Size
433 B
Last Changed
last year

Provides helpers for building a multi-step wizard interface.

Demo
​

source

User information
Billing address
Terms
Payment
User information
First name:
Last name:
Next
Form
{
  "firstName": "Jon",
  "lastName": "",
  "billingAddress": "",
  "contractAccepted": false,
  "carbonOffsetting": false,
  "payment": "credit-card"
}
Wizard
{
  "steps": {
    "user-information": {
      "title": "User information"
    },
    "billing-address": {
      "title": "Billing address"
    },
    "terms": {
      "title": "Terms"
    },
    "payment": {
      "title": "Payment"
    }
  },
  "stepNames": [
    "user-information",
    "billing-address",
    "terms",
    "payment"
  ],
  "index": 0,
  "current": {
    "title": "User information"
  },
  "next": "billing-address",
  "isFirst": true,
  "isLast": false
}
Usage
​
Steps as array
​
js
import { useStepper } from '@vueuse/core'

const {
  steps,
  stepNames,
  index,
  current,
  next,
  previous,
  isFirst,
  isLast,
  goTo,
  goToNext,
  goToPrevious,
  goBackTo,
  isNext,
  isPrevious,
  isCurrent,
  isBefore,
  isAfter,
} = useStepper([
  'billing-address',
  'terms',
  'payment',
])

// Access the step through `current`
console.log(current.value) // 'billing-address'
Steps as object
​
js
import { useStepper } from '@vueuse/core'

const {
  steps,
  stepNames,
  index,
  current,
  next,
  previous,
  isFirst,
  isLast,
  goTo,
  goToNext,
  goToPrevious,
  goBackTo,
  isNext,
  isPrevious,
  isCurrent,
  isBefore,
  isAfter,
} = useStepper({
  'user-information': {
    title: 'User information',
  },
  'billing-address': {
    title: 'Billing address',
  },
  'terms': {
    title: 'Terms',
  },
  'payment': {
    title: 'Payment',
  },
})

// Access the step object through `current`
console.log(current.value.title) // 'User information'
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jelle Roorda
Ostap Brehin
sun0day
Enzo Innocenzi
Changelog
​
v8.9.0 on 7/6/2022
6b016 - feat: new function (#1754)
usePrevious | VueUse

usePrevious
​
Category
Utilities
Export Size
260 B
Last Changed
8 months ago

Holds the previous value of a ref.

Usage
​
ts
import { ref } from 'vue'
import { usePrevious } from '@vueuse/core'

const counter = ref('Hello')
const previous = usePrevious(counter)

console.log(previous.value) // undefined

counter.value = 'World'

console.log(previous.value) // Hello
Source
​

Source • Docs

Contributors
​
Anthony Fu
Changelog
​
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef
v9.12.0 on 1/29/2023
e101f - feat: new function
useMemoize | VueUse

useMemoize
​
Category
Utilities
Export Size
403 B
Last Changed
8 months ago

Cache results of functions depending on arguments and keep it reactive. It can also be used for asynchronous functions and will reuse existing promises to avoid fetching the same data at the same time.

TIP

The results are not cleared automatically. Call clear() in case you no longer need the results or use own caching mechanism to avoid memory leaks.

Usage
​
TypeScript
ts
import { useMemoize } from '@vueuse/core'
const getUser = useMemoize(
  async (userId: number): Promise<UserData> =>
    axios.get(`users/${userId}`).then(({ data }) => data),
)
const user1 = await getUser(1) // Request users/1
const user2 = await getUser(2) // Request users/2
// ...
const user1 = await getUser(1) // Retrieve from cache
// ...
const user1 = await getUser.load(1) // Request users/1
// ...
getUser.delete(1) // Delete cache from user 1
getUser.clear() // Clear full cache

Combine with computed or asyncComputed to achieve reactivity:

ts
const user1 = asyncComputed(() => getUser(1))
// ...
await getUser.load(1) // Will also update user1
Resolving cache key
​

The key for caching is determined by the arguments given to the function and will be serialized by default with JSON.stringify. This will allow equal objects to receive the same cache key. In case you want to customize the key you can pass getKey

TypeScript
ts
const getUser = useMemoize(
  async (userId: number, headers: AxiosRequestHeaders): Promise<UserData> =>
    axios.get(`users/${userId}`, { headers }).then(({ data }) => data),
  {
    // Use only userId to get/set cache and ignore headers
    getKey: (userId, headers) => userId,
  },
)

WARNING

For Vue 2 the key has to be a string or number

Customize cache mechanism
​

By default, the results are cached within a Map (normal object for Vue 2). You can implement your own mechanism by passing cache as options with following structure:

TypeScript
ts
export interface MemoizeCache<Key, Value> {
  /**
   * Get value for key
   */
  get(key: Key): Value | undefined
  /**
   * Set value for key
   */
  set(key: Key, value: Value): void
  /**
   * Return flag if key exists
   */
  has(key: Key): boolean
  /**
   * Delete value for key
   */
  delete(key: Key): void
  /**
   * Clear cache
   */
  clear(): void
}
Source
​

Source • Docs

Contributors
​
Anthony Fu
Mikhailov Nikita
Jelf
freakzlike
Changelog
​
v9.2.0 on 9/5/2022
06ad0 - fix: allow number in getKey (#2074)
v8.9.3 on 7/14/2022
5ef88 - fix!: rename type UseMemoizedFn to UseMemoizeReturn and new type UseMemoizeOptions (#1872)
useOffsetPagination | VueUse

useOffsetPagination
​
Category
Utilities
Export Size
650 B
Last Changed
4 months ago

Reactive offset pagination.

Demo
​

source

total:
80
pageCount:
8
currentPageSize:
10
currentPage:
1
isFirstPage:
true
isLastPage:
false
prev12345678next
id	name
Usage
​
TypeScript
ts
import { useOffsetPagination } from '@vueuse/core'
function fetchData({
  currentPage,
  currentPageSize,
}: {
  currentPage: number
  currentPageSize: number
}) {
  fetch(currentPage, currentPageSize).then((responseData) => {
    data.value = responseData
  })
}
const {
  currentPage,
  currentPageSize,
  pageCount,
  isFirstPage,
  isLastPage,
  prev,
  next,
} = useOffsetPagination({
  total: database.value.length,
  page: 1,
  pageSize: 10,
  onPageChange: fetchData,
  onPageSizeChange: fetchData,
})
Component Usage
​

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

html
<UseOffsetPagination
  v-slot="{
    currentPage,
    currentPageSize,
    next,
    prev,
    pageCount,
    isFirstPage,
    isLastPage
  }"
  :total="database.length"
  @page-change="fetchData"
  @page-size-change="fetchData"
>
  <div class="gap-x-4 gap-y-2 grid-cols-2 inline-grid items-center">
    <div opacity="50">
      total:
    </div>
    <div>{{ database.length }}</div>
    <div opacity="50">
      pageCount:
    </div>
    <div>{{ pageCount }}</div>
    <div opacity="50">
      currentPageSize:
    </div>
    <div>{{ currentPageSize }}</div>
    <div opacity="50">
      currentPage:
    </div>
    <div>{{ currentPage }}</div>
    <div opacity="50">
      isFirstPage:
    </div>
    <div>{{ isFirstPage }}</div>
    <div opacity="50">
      isLastPage:
    </div>
    <div>{{ isLastPage }}</div>
  </div>
  <div>
    <button :disabled="isFirstPage" @click="prev">
      prev
    </button>
    <button :disabled="isLastPage" @click="next">
      next
    </button>
  </div>
</UseOffsetPagination>

Component event supported props event callback and event listener.

event listener:

html
<UseOffsetPagination
  v-slot="{
    currentPage,
    currentPageSize,
    next,
    prev,
    pageCount,
    isFirstPage,
    isLastPage
  }"
  :total="database.length"
  @page-change="fetchData"
  @page-size-change="fetchData"
  @page-count-change="onPageCountChange"
>
  <!-- your code -->
</UseOffsetPagination>

or props event callback:

html
<UseOffsetPagination
  v-slot="{
    currentPage,
    currentPageSize,
    next,
    prev,
    pageCount,
    isFirstPage,
    isLastPage
  }"
  :total="database.length"
  :on-page-change="fetchData"
  :on-page-size-change="fetchData"
  :on-page-count-change="onPageCountChange"
>
  <!-- your code -->
</UseOffsetPagination>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
LJX
vaakian X
JD Solanki
Curt Grimes
webfansplz
三咲智子
Jelf
Changelog
​
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.1.0 on 8/4/2022
b6503 - fix: min value for pageCount should be 1 (#2001)
v9.0.0-beta.1 on 7/20/2022
85c5f - fix: incorrectly currentPageSize value (#1949)
v8.9.2 on 7/12/2022
27125 - feat(math)!: move useClamp to @vueuse/math (#1810)
useEventBus | VueUse

useEventBus
​
Category
Utilities
Export Size
332 B
Last Changed
2 months ago

A basic event bus.

Demo
​

source

News channel:
Broadcast
Television:
--- no signal ---
Usage
​
TypeScript
ts
import { useEventBus } from '@vueuse/core'
const bus = useEventBus<string>('news')
function listener(event: string) {
  console.log(`news: ${event}`)
}
// listen to an event
const unsubscribe = bus.on(listener)
// fire an event
bus.emit('The Tokyo Olympics has begun')
// unregister the listener
unsubscribe()
// or
bus.off(listener)
// clearing all listeners
bus.reset()

Listeners registered inside of components setup will be unregistered automatically when the component gets unmounted.

TypeScript
​

Using EventBusKey is the key to bind the event type to the key, similar to Vue's InjectionKey util.

TypeScript
ts
// fooKey.ts
import type { EventBusKey } from '@vueuse/core'
export const fooKey: EventBusKey<{ name: foo }> = Symbol('symbol-key')
ts
import { useEventBus } from '@vueuse/core'

import { fooKey } from './fooKey'

const bus = useEventBus(fooKey)

bus.on((e) => {
  // `e` will be `{ name: foo }`
})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
TuiMao233
jahnli
丶远方
Haoqun Jiang
sun0day
webfansplz
Jairo Blatt
Changelog
​
v10.0.0-beta.0 on 3/14/2023
dd514 - fix(useEventBus,createEventHook)!: dedupe registration of the same function (#2748)
37ec7 - fix: use ts-ignore instead of ts-expect-error for version-specifc errors (#2802)
useCycleList | VueUse

useCycleList
​
Category
Utilities
Export Size
463 B
Last Changed
7 months ago

Cycle through a list of items.

Learn how to use useCycleList to create an image carousel with this FREE video lesson from Vue School!
Demo
​

source

Dog
PrevNext
Usage
​
ts
import { useCycleList } from '@vueuse/core'

const { state, next, prev } = useCycleList([
  'Dog',
  'Cat',
  'Lizard',
  'Shark',
  'Whale',
  'Dolphin',
  'Octopus',
  'Seal',
])

console.log(state.value) // 'Dog'

prev()

console.log(state.value) // 'Seal'
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
xiaofan
Helio S. Junior
Waleed Khaled
Jelf
markthree
lsdsjy
Changelog
​
v10.1.0 on 4/22/2023
659b2 - fix: correctly wrap list with ref (#2988)
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
v10.0.0-beta.0 on 3/14/2023
b65c2 - feat: allow receiving reactive list (#2864)
v9.1.0 on 8/4/2022
fa2f6 - feat: support MaybeRef for initialValue (#2025)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
useCloned | VueUse

useCloned
​
Category
Utilities
Export Size
499 B
Last Changed
5 months ago

Reactive clone of a ref. By default, it use JSON.parse(JSON.stringify()) to do the clone.

Demo
​

source

reset
Usage
​
ts
import { useCloned } from '@vueuse/core'

const original = ref({ key: 'value' })

const { cloned } = useCloned(original)

original.value.key = 'some new value'

console.log(cloned.value.key) // 'some new value'
Manual cloning
​
ts
import { useCloned } from '@vueuse/core'

const original = ref({ key: 'value' })

const { cloned, sync } = useCloned(original, { manual: true })

original.value.key = 'manual'

console.log(cloned.value.key) // 'value'

sync()

console.log(cloned.value.key)// 'manual'
Custom Clone Function
​

Using klona for example:

ts
import { useCloned } from '@vueuse/core'
import { klona } from 'klona'

const original = ref({ key: 'value' })

const { cloned, sync } = useCloned(original, { clone: klona })
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Jeff Yang (楊德誠)
Akkapon Chainarong
Eduardo Wesley
Mikhailov Nikita
Changelog
​
v10.2.0 on 6/16/2023
6d630 - fix: check for getter function to watch (#3142)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
v9.2.0 on 9/5/2022
369e1 - feat(useVModel): support clone option (#2022)
0a0a1 - feat: new function (#2045)
useConfirmDialog | VueUse

useConfirmDialog
​
Category
Utilities
Export Size
418 B
Last Changed
2 months ago

Creates event hooks to support modals and confirmation dialog chains.

Functions can be used on the template, and hooks are a handy skeleton for the business logic of modals dialog or other actions that require user confirmation.

Demo
​

source

Click to Show Modal Dialog
Functions and hooks
​
reveal() - triggers onReveal hook and sets revealed.value to true. Returns promise that resolves by confirm() or cancel().
confirm() - sets isRevealed.value to false and triggers onConfirm hook.
cancel() - sets isRevealed.value to false and triggers onCancel hook.
Basic Usage
​
Using hooks
​
html
<script setup>
import { useConfirmDialog } from '@vueuse/core'

const {
  isRevealed,
  reveal,
  confirm,
  cancel,
  onReveal,
  onConfirm,
  onCancel,
} = useConfirmDialog()
</script>

<template>
  <button @click="reveal">Reveal Modal</button>

  <teleport to="body">
    <div v-if="isRevealed" class="modal-bg">
      <div class="modal">
        <h2>Confirm?</h2>
        <button @click="confirm">Yes</button>
        <button @click="cancel">Cancel</button>
      </div>
    </div>
  </teleport>
</template>
Promise
​

If you prefer working with promises:

html
<script setup>
import { useConfirmDialog } from '@vueuse/core'

const {
  isRevealed,
  reveal,
  confirm,
  cancel,
} = useConfirmDialog()

const openDialog = async () => {
  const { data, isCanceled } = await reveal()
  if (!isCanceled) {
    console.log(data)
  }
}
</script>

<template>
  <button @click="openDialog">Show Modal</button>

  <teleport to="body">
    <div v-if="isRevealed" class="modal-layout">
      <div class="modal">
        <h2>Confirm?</h2>
        <button @click="confirm(true)">Yes</button>
        <button @click="confirm(false)">No</button>
      </div>
    </div>
  </teleport>
</template>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Roman Harmyder
糠帅傅
Waleed Khaled
丶远方
Ryan Wu
Changelog
​
No recent changes
useCached | VueUse

useCached
​
Category
Utilities
Export Size
169 B
Last Changed
2 years ago

Cache a ref with a custom comparator.

Demo
​

source

Value: 42
Extra: 0
Cached Value: 42
Cached Extra: 0
Temp Value: 
Local Extra: 
Sync
Usage
​
TypeScript
ts
import { useCached } from '@vueuse/core'
interface Data {
  value: number
  extra: number
}
const source = ref<Data>({ value: 42, extra: 0 })
const cached = useCached(source, (a, b) => a.value === b.value)
source.value = {
  value: 42,
  extra: 1,
}
console.log(cached.value) // { value: 42, extra: 0 }
source.value = {
  value: 43,
  extra: 1,
}
console.log(cached.value) // { value: 43, extra: 1 }
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
sun0day
lvjiaxuan
Wenlu Wang
Changelog
​
No recent changes
useBase64 | VueUse

useBase64
​
Category
Utilities
Export Size
769 B
Last Changed
8 months ago

Reactive base64 transforming. Supports plain text, buffer, files, canvas, objects, maps, sets and images.

Demo
​

source

Text Input
Base64
Buffer Input
new ArrayBuffer(1024)
Base64
File Input
Base64
Image Input
Base64
Usage
​
TypeScript
ts
import { Ref, ref } from 'vue'
import { useBase64 } from '@vueuse/core'
const text = ref('')
const { base64 } = useBase64(text)

If you use object, array, map or set you can provide serializer in options. Otherwise, your data will be serialized by default serializer. Objects and arrays will be transformed in string by JSON.stringify. Map and set will be transformed in object and array respectively before stringify.

Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
丶远方
Mikhailov Nikita
wheat
jelf
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
0a72b - feat(toValue): rename resolveUnref to toValue
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
v8.8.0 on 7/6/2022
1fd34 - feat: accept objects (#1706)
useAsyncQueue | VueUse

useAsyncQueue
​
Category
Utilities
Export Size
511 B
Last Changed
3 months ago

Executes each asynchronous task sequentially and passes the current task result to the next task

Demo
​

source

activeIndex: 1
result: [ { "state": "fulfilled", "data": 1000 }, { "state": "fulfilled", "data": 2000 } ]
Usage
​
TypeScript
ts
import { useAsyncQueue } from '@vueuse/core'
function p1() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(1000)
    }, 10)
  })
}
function p2(result: number) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(1000 + result)
    }, 20)
  })
}
const { activeIndex, result } = useAsyncQueue([p1, p2])
console.log(activeIndex.value) // current pending task index
console.log(result) // the tasks result
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
ethansnow2012
cross-origin
Okoro Redemption
donotloveshampo
Yugang Cao
webfansplz
Changelog
​
v10.4.0 on 8/25/2023
22e26 - feat: support in infinite tasks in typescript (#3333)
v10.2.0 on 6/16/2023
7da7c - feat: add options.signal parameter (#3033)
useTimeAgo | VueUse

useTimeAgo
​
Category
Time
Export Size
1.63 kB
Last Changed
2 months ago

Reactive time ago. Automatically update the time ago string when the time changes.

Demo
​

source

just now
0ms
Usage
​
js
import { useTimeAgo } from '@vueuse/core'

const timeAgo = useTimeAgo(new Date(2021, 0, 1))
Component Usage
​

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

html
<UseTimeAgo v-slot="{ timeAgo }" :time="new Date(2021, 0, 1)">
  Time Ago: {{ timeAgo }}
</UseTimeAgo>
Non-Reactivity Usage
​

In case you don't need the reactivity, you can use the formatTimeAgo function to get the formatted string instead of a Ref.

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

const timeAgo = formatTimeAgo(new Date(2021, 0, 1)) // string
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
WORMSS
vaakian X
Demian
Joaquín Sánchez
Connor 'Birb' McCormick
836334258
sun0day
azaleta
vaakian X
Jelf
wheat
Alex Kozack
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.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.9.0 on 12/23/2022
bb0fd - fix(formatTimeAgo): typo foramtTimeAgo -> formatTimeAgo (#2568)
v9.8.0 on 12/20/2022
f40a0 - fix: rounding unit fallback
9293c - feat: non-reactive version formatTimeAgo
v9.7.0 on 12/16/2022
324de - feat: custom units, number rounding
a7dc6 - feat: add floor and ceil value calculation (#2543)
0c333 - fix: add showSecond prop to component (#2547)
v9.3.0 on 9/26/2022
553f0 - feat: new showSecond option (#2209)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
createUnrefFn | VueUse

createUnrefFn
​
Category
Utilities
Export Size
166 B
Last Changed
8 months ago
Related
reactify

Make a plain function accepting ref and raw values as arguments. Returns the same value the unconverted function returns, with proper typing.

TIP

Make sure you're using the right tool for the job. Using reactify might be more pertinent in some cases where you want to evaluate the function on each changes of it's arguments.

Usage
​
ts
import { ref } from 'vue'
import { createUnrefFn } from '@vueuse/core'

const url = ref('https://httpbin.org/post')
const data = ref({ foo: 'bar' })

function post(url, data) {
  return fetch(url, { data })
}
const unrefPost = createUnrefFn(post)

post(url, data) /* ❌ Will throw an error because the arguments are refs */
unrefPost(url, data) /* ✔️ Will Work because the arguments will be auto unref */
Source
​

Source • Docs

Contributors
​
Anthony Fu
Stanley Horwood
Changelog
​
No recent changes
computedAsync | VueUse

computedAsync
​
Category
Reactivity
Export Size
358 B
Last Changed
9 months ago
Alias
asyncComputed

Computed for async functions

Usage
​
js
import { ref } from 'vue'
import { computedAsync } from '@vueuse/core'

const name = ref('jack')

const userInfo = computedAsync(
  async () => {
    return await mockLookUp(name.value)
  },
  null, // initial state
)
Evaluation State
​

You will need to pass a ref to track if the async function is evaluating.

js
import { ref } from 'vue'
import { computedAsync } from '@vueuse/core'

const evaluating = ref(false)

const userInfo = computedAsync(
  async () => { /* your logic */ },
  null,
  evaluating,
)
onCancel
​

When the computed source changed before the previous async function gets resolved, you may want to cancel the previous one. Here is an example showing how to incorporate with the fetch API.

js
const packageName = ref('@vueuse/core')

const downloads = computedAsync(async (onCancel) => {
  const abortController = new AbortController()

  onCancel(() => abortController.abort())

  return await fetch(
    `https://api.npmjs.org/downloads/point/last-week/${packageName.value}`,
    { signal: abortController.signal },
  )
    .then(response => response.ok ? response.json() : { downloads: '—' })
    .then(result => result.downloads)
}, 0)
Lazy
​

By default, computedAsync will start resolving immediately on creation, specify lazy: true to make it start resolving on the first accessing.

js
import { ref } from 'vue'
import { computedAsync } from '@vueuse/core'

const evaluating = ref(false)

const userInfo = computedAsync(
  async () => { /* your logic */ },
  null,
  { lazy: true, evaluating },
)
Caveats
​

Just like Vue's built-in computed function, computedAsync does dependency tracking and is automatically re-evaluated when dependencies change. Note however that only dependency referenced in the first call stack are considered for this. In other words: Dependencies that are accessed asynchronously will not trigger re-evaluation of the async computed value.

As opposed to Vue's built-in computed function, re-evaluation of the async computed value is triggered whenever dependencies are changing, regardless of whether its result is currently being tracked or not.

Source
​

Source • Docs

Contributors
​
Anthony Fu
xiankaiqun
Icey Wu
sun0day
Yugang Cao
Bodo Graumann
Changelog
​
v10.0.0-beta.0 on 3/14/2023
23c9d - feat!: set shallow defalut to true (#2621)
v9.11.0 on 1/17/2023
a0656 - feat: introduce shadow option (#2616)
useVModels | VueUse

useVModels
​
Category
Component
Export Size
567 B
Last Changed
2 months ago
Related
useVModel

Shorthand for props v-model binding. Think it like toRefs(props) but changes will also trigger emit.

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

export default {
  props: {
    foo: String,
    bar: Number,
  },
  setup(props, { emit }) {
    const { foo, bar } = useVModels(props, emit)

    console.log(foo.value) // props.foo
    foo.value = 'foo' // emit('update:foo', 'foo')
  },
}
Source
​

Source • Docs

Contributors
​
Anthony Fu
Mikhailov Nikita
Jelf
sondh0127
William T. Kirby
Alex Kozack
ordago
Emīls Gulbis
Changelog
​
v10.5.0 on 10/7/2023
51f01 - fix: type error with passive: true (#3362)
v8.9.3 on 7/14/2022
71550 - fix(useVModel)!: rename type VModelOptions to UseVModelOptions (#1894)
useSorted | VueUse

useSorted
​
Category
Array
Export Size
366 B
Last Changed
2 months ago

reactive sort array

Demo
​

source

input:
random
output: [ "13", "17", "41", "49", "53", "59", "67", "72", "81", "98", "99" ]
object property sort:
input:
[ { "name": "John", "age": 40 }, { "name": "Jane", "age": 20 }, { "name": "Joe", "age": 30 }, { "name": "Jenny", "age": 22 } ]
output:
[ { "name": "Jane", "age": 20 }, { "name": "Jenny", "age": 22 }, { "name": "Joe", "age": 30 }, { "name": "John", "age": 40 } ]
Usage
​
ts
import { useSorted } from '@vueuse/core'

// general sort
const source = [10, 3, 5, 7, 2, 1, 8, 6, 9, 4]
const sorted = useSorted(source)
console.log(sorted.value) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(source) // [10, 3, 5, 7, 2, 1, 8, 6, 9, 4]

// object sort
const objArr = [{
  name: 'John',
  age: 40,
}, {
  name: 'Jane',
  age: 20,
}, {
  name: 'Joe',
  age: 30,
}, {
  name: 'Jenny',
  age: 22,
}]
const objSorted = useSorted(objArr, (a, b) => a.age - b.age)
dirty mode
​

dirty mode will change the source array.

ts
const source = ref([10, 3, 5, 7, 2, 1, 8, 6, 9, 4])
const sorted = useSorted(source, (a, b) => a - b, {
  dirty: true,
})
console.log(source)// output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Kasper Seweryn
Jelf
Changelog
​
v10.3.0 on 7/30/2023
33a12 - feat: accept getter function as source (#3249)
v9.3.1 on 10/17/2022
feaa1 - feat: new function (#1799)
useVModel | VueUse

useVModel
​
Category
Component
Export Size
533 B
Last Changed
4 months ago
Related
useVModels

Shorthand for v-model binding, props + emit -> ref

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

export default {
  setup(props, { emit }) {
    const data = useVModel(props, 'data', emit)

    console.log(data.value) // props.data
    data.value = 'foo' // emit('update:data', 'foo')
  },
}
<script setup>
​
vue
<script lang="ts" setup>
import { useVModel } from '@vueuse/core'

const props = defineProps<{
  modelValue: string
}>()
const emit = defineEmits(['update:modelValue'])

const data = useVModel(props, 'modelValue', emit)
</script>
Source
​

Source • Docs

Contributors
​
Anthony Fu
Jelf
webfansplz
motian
objectisundefined
Alex Liu
白雾三语
Eduardo Wesley
Roman Meshcheryakov
久染
chaii3
Tmk
wheat
sondh0127
Zenthae
Eduardo San Martin Morote
lstoeferle
Alex Kozack
Homyee King
Prabu Rangki
Leonidas Arvanitis
yangger
Changelog
​
v10.4.0 on 8/25/2023
48f4c - fix: clone set to true triggered infinite loop (#3097)
v10.2.0 on 6/16/2023
7d788 - feat: improve types overload (#3055)
v10.0.0-beta.5 on 4/13/2023
cb644 - refactor!: remove isFunction and isString utils
v10.0.0-beta.1 on 3/23/2023
f8a53 - feat: add shouldEmit hook (#2836)
v9.2.0 on 9/5/2022
369e1 - feat: support clone option (#2022)
v8.9.3 on 7/14/2022
10f5a - fix: fix compact with 2.7, fix #1745 (#1898)
71550 - fix!: rename type VModelOptions to UseVModelOptions (#1894)
v8.9.2 on 7/12/2022
53319 - feat: compact with 2.7, fix #1745 (#1798)
useTemplateRefsList | VueUse

useTemplateRefsList
​
Category
Component
Export Size
177 B
Last Changed
2 years ago

Shorthand for binding refs to template elements and components inside v-for.

WARNING

This function only works for Vue 3

Demo
​

source

12345
IncDec
Open the console to see the output
Usage
​
html
<template>
  <div v-for="i of 5" :key="i" :ref="refs.set"></div>
</template>

<script setup lang="ts">
import { onUpdated } from 'vue'
import { useTemplateRefsList } from '@vueuse/core'

const refs = useTemplateRefsList<HTMLDivElement>()

onUpdated(() => {
  console.log(refs)
})
</script>
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
bjym
Changelog
​
No recent changes
useMounted | VueUse

useMounted
​
Category
Component
Export Size
156 B
Last Changed
2 months ago

Mounted state in ref.

Demo
​

source

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

const isMounted = useMounted()

Which is essentially a shorthand of:

ts
const isMounted = ref(false)

onMounted(() => {
  isMounted.value = true
})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
Changelog
​
v10.0.0-beta.3 on 4/13/2023
1aab1 - fix: check for the current instance
useCurrentElement | VueUse

useCurrentElement
​
Category
Component
Export Size
355 B
Last Changed
last year

Get the DOM element of current component as a ref.

Demo
​

source

Open your console.log to see the element
Usage
​
ts
import { useCurrentElement } from '@vueuse/core'

const el = useCurrentElement() // ComputedRef<Element>
Caveats
​

This functions uses $el under the hood.

Value of the ref will be undefined until the component is mounted.

For components with a single root element, it will point to that element.
For components with text root, it will point to the text node.
For components with multiple root nodes, it will be the placeholder DOM node that Vue uses to keep track of the component's position in the DOM.

It's recommend to only use this function for components with a single root element.

Source
​

Source • Demo • Docs

Contributors
​
vaakian X
Anthony Fu
Changelog
​
v9.1.1 on 8/23/2022
c534e - fix(useActiveElement): use computedWithControl instead of counter ref (#2093)
unrefElement | VueUse

unrefElement
​
Category
Component
Export Size
165 B
Last Changed
8 months ago

Retrieves the underlying DOM element from a Vue ref or component instance

Usage
​
html
<template>
  <div ref="div"/>
  <HelloWorld ref="hello"/>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { unrefElement } from '@vueuse/core'

const div = ref() // will be bound to the <div> element
const hello = ref() // will be bound to the HelloWorld Component

onMounted(() => {
  console.log(unrefElement(div)) // the <div> element
  console.log(unrefElement(hello)) // the root element of the HelloWorld Component
})
</script>
Source
​

Source • Docs

Contributors
​
Anthony Fu
Henrik Kampshoff
Nebula
Julian Meinking
Jelf
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.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)
v8.7.4 on 6/18/2022
3d846 - fix: revert #1657
v8.7.0 on 6/16/2022
050da - fix: don't return the Vue instance when $el is null/undefined (#1657)
computedInject | VueUse

computedInject
​
Category
Component
Export Size
183 B
Last Changed
last year

Combine computed and inject

Demo
​

source

Array
[
  {
    "key": 1,
    "value": "1"
  },
  {
    "key": 2,
    "value": "2"
  },
  {
    "key": 3,
    "value": "3"
  }
]
Computed Array
[
  {
    "key": 0,
    "value": "all"
  },
  {
    "key": 1,
    "value": "1"
  },
  {
    "key": 2,
    "value": "2"
  },
  {
    "key": 3,
    "value": "3"
  }
]
Usage
​

In Provider Component

TypeScript
ts
import type { InjectionKey, Ref } from 'vue'
import { provide, ref } from 'vue'
interface Item {
  key: number
  value: string
}
export const ArrayKey: InjectionKey<Ref<Item[]>> = Symbol('symbol-key')
const array = ref([
  { key: 1, value: '1' },
  { key: 2, value: '2' },
  { key: 3, value: '3' },
])
provide(ArrayKey, array)

In Receiver Component

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

import { ArrayKey } from './provider'

const computedArray = computedInject(ArrayKey, (source) => {
  const arr = [...source.value]
  arr.unshift({ key: 0, value: 'all' })
  return arr
})
Source
​

Source • Demo • Docs

Contributors
​
Anthony Fu
丶远方
wheat
MinatoHikari
Changelog
​
No recent changes