

VueUse
======

Collection of Vue Composition Utilities



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/>

Get Started
===========


[Learn VueUse with video](https://vueschool.io/courses/vueuse-for-everyone?friend=vueuse)VueUse is a collection of utility functions based on [Composition API](https://v3.vuejs.org/guide/composition-api-introduction.html). We assume you are already familiar with the basic ideas of [Composition API](https://v3.vuejs.org/guide/composition-api-introduction.html) before you continue.


Installation
------------



> 🎩 From v4.0, it works for Vue 2 & 3 **within a single package** by the power of [vue-demi](https://github.com/vueuse/vue-demi)!
> 
> 




```
npm i @vueuse/core
```


[Add ons](https://vueuse.org/add-ons) | [Nuxt Module](index#nuxt)



> From v6.0, VueUse requires `vue` >= v3.2 or `@vue/composition-api` >= v1.1
> 
> 


###### Demos


* [Vite + Vue 3](https://github.com/vueuse/vueuse-vite-starter)
* [Nuxt 3 + Vue 3](https://github.com/antfu/vitesse-nuxt3)
* [Webpack + Vue 3](https://github.com/vueuse/vueuse-vue3-example)
* [Nuxt 2 + Vue 2](https://github.com/antfu/vitesse-nuxt-bridge)
* [Vue CLI + Vue 2](https://github.com/vueuse/vueuse-vue2-example)


### CDN




```
<script src="https://unpkg.com/@vueuse/shared"></script>
<script src="https://unpkg.com/@vueuse/core"></script>
```


It will be exposed to global as `window.VueUse`


### Nuxt


From v7.2.0, we shipped a Nuxt module to enable auto importing for Nuxt 3 and Nuxt Bridge.




```
npm i -D @vueuse/nuxt @vueuse/core
```


Nuxt 3




```
// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    '@vueuse/nuxt',
  ],
})
```


Nuxt 2




```
// nuxt.config.js
export default {
  buildModules: [
    '@vueuse/nuxt',
  ],
}
```


And then use VueUse function anywhere in your Nuxt app. For example:




```
<script setup lang="ts">
const { x, y } = useMouse()
</script>

<template>
  <div>pos: {{x}}, {{y}}</div>
</template>
```


Usage Example
-------------


Simply importing the functions you need from `@vueuse/core`




```
import { useLocalStorage, useMouse, usePreferredDark } from '@vueuse/core'

export default {
  setup() {
    // tracks mouse position
    const { x, y } = useMouse()

    // is user prefers dark theme
    const isDark = usePreferredDark()

    // persist state in localStorage
    const store = useLocalStorage(
      'my-storage',
      {
        name: 'Apple',
        color: 'red',
      },
    )

    return { x, y, isDark, store }
  },
}
```


Refer to [functions list](../functions) for more details.



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/guide/>

Components
==========


In v5.0, we introduced a new package, `@vueuse/components` providing renderless component versions of composable functions.


Install
-------




```
$ npm i @vueuse/core @vueuse/components
```


Usage
-----


For example of [`onClickOutside`](../core/onclickoutside/index) instead of binding the component ref for functions to consume:




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

const el = ref()

function close () {
  /* ... */
}

onClickOutside(el, close)
</script>

<template>
  <div ref="el">
    Click Outside of Me
  </div>
</template>
```


We can now use the renderless component which the binding is done automatically:




```
<script setup>
import { OnClickOutside } from '@vueuse/components'

function close () {
  /* ... */
}
</script>

<template>
  <OnClickOutside @trigger="close">
    <div>
      Click Outside of Me
    </div>
  </OnClickOutside>
</template>
```


Return Value
------------


You can access return values with `v-slot`:




```
<UseMouse v-slot="{ x, y }">
  x: {{ x }}
  y: {{ y }}
</UseMouse>
```




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


Refer to each function's documentation for the detailed usage of component style.



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/guide/components>

Best Practice
=============


### Destructuring


Most of the functions in VueUse return an **object of refs** that you can use [ES6's object destructure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax on to take what you need. For example:




```
import { useMouse } from '@vueuse/core'

// "x" and "y" are refs
const { x, y } = useMouse()

console.log(x.value)

const mouse = useMouse()

console.log(mouse.x.value)
```


If you prefer to use them as object properties style, you can unwrap the refs by using `reactive()`. For example:




```
import { reactive } from 'vue'
import { useMouse } from '@vueuse/core'

const mouse = reactive(useMouse())

// "x" and "y" will be auto unwrapped, no `.value` needed
console.log(mouse.x)
```


### Side-effect Clean Up


Similar to Vue's `watch` and `computed` that will be disposed when the component is unmounted, VueUse's functions also clean up the side-effects automatically.


For example, [`useEventListener`](../core/useeventlistener/index) will call `removeEventListener` when the component is unmounted so you don't need to worry about it.




```
// will cleanup automatically
useEventListener('mousemove', () => {})
```


All VueUse functions follow this convention.


To manually dispose the side-effects, some function returns a stop handler just like the `watch` function. For example:




```
const stop = useEventListener('mousemove', () => {})

// ...

// unregister the event listener manually
stop()
```


While not all function return the handler, a more general solution is to use the [`effectScope` API](https://vuejs.org/api/reactivity-advanced.html#effectscope) from Vue.




```
import { effectScope } from 'vue'

const scope = effectScope()

scope.run(() => {
  // ...

  useEventListener('mousemove', () => {})
  onClickOutside(el, () => {})
  watch(source, () => {})
})

// all composables called inside `scope.run` will be disposed
scope.stop()
```


You can learn more about effect scope in [this RFC](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0041-reactivity-effect-scope.md).


### Passing Ref as Argument


In Vue, we use the `setup()` function to construct the "connections" between the data and logics. To make it flexible, most of the VueUse function also accepts ref version of the arguments.


Taking [`useTitle`](../core/usetitle/index) as an example:


###### Normal usage


Normally [`useTitle`](../core/usetitle/index) return a ref that reflects to the page's title. When you assign new value to the ref, it automatically updates the title.




```
const isDark = useDark()
const title = useTitle('Set title')

watch(isDark, () => {
  title.value = isDark.value ? '🌙 Good evening!' : '☀️ Good morning!'
})
```


###### Connection usage


If you think in "connection", you can instead passing a ref that make it bind to the page's title.




```
const isDark = useDark()
const title = computed(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')

useTitle(title)
```


###### Reactive Getter


Since VueUse 9.0, we introduce a new convention for passing "Reactive Getter" as the argument. Which works great with reactive object and [Reactivity Transform](https://vuejs.org/guide/extras/reactivity-transform.html#reactivity-transform).




```
const isDark = useDark()

useTitle(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')
```



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/guide/best-practice>

Configurations
==============


These show the general configurations for most of the functions in VueUse.


### Event Filters


From v4.0, we provide the Event Filters system to give the flexibility to control when events will get triggered. For example, you can use `throttleFilter` and `debounceFilter` to control the event trigger rate:




```
import { debounceFilter, throttleFilter, useLocalStorage, useMouse } from '@vueuse/core'

// changes will write to localStorage with a throttled 1s
const storage = useLocalStorage('my-key', { foo: 'bar' }, { eventFilter: throttleFilter(1000) })

// mouse position will be updated after mouse idle for 100ms
const { x, y } = useMouse({ eventFilter: debounceFilter(100) })
```


Moreover, you can utilize `pausableFilter` to temporarily pause some events.




```
import { pausableFilter, useDeviceMotion } from '@vueuse/core'

const motionControl = pausableFilter()

const motion = useDeviceMotion({ eventFilter: motionControl.eventFilter })

motionControl.pause()

// motion updates paused

motionControl.resume()

// motion updates resumed
```


### Reactive Timing


VueUse's functions follow Vue's reactivity system defaults for [flush timing](https://vuejs.org/guide/essentials/watchers.html#callback-flush-timing) where possible.


For `watch`-like composables (e.g. `pausableWatch`, `whenever`, [`useStorage`](../core/usestorage/index) [`useRefHistory`](../core/userefhistory/index) the default is `{ flush: 'pre' }`. Which means they will buffer invalidated effects and flush them asynchronously. This avoids unnecessary duplicate invocation when there are multiple state mutations happening in the same "tick".


In the same way as with `watch`, VueUse allows you to configure the timing by passing the `flush` option:




```
const { pause, resume } = pausableWatch(
  () => {
    // Safely access updated DOM
  },
  { flush: 'post' },
)
```


**flush option (default: `'pre'`)**


* `'pre'`: buffers invalidated effects in the same 'tick' and flushes them before rendering
* `'post'`: async like 'pre' but fires after component updates so you can access the updated DOM
* `'sync'`: forces the effect to always trigger synchronously


**Note:** For `computed`-like composables (e.g. [`syncRef`](../shared/syncref/index) `controlledComputed`), when flush timing is configurable, the default is changed to `{ flush: 'sync' }` to align them with the way computed refs works in Vue.


### Configurable Global Dependencies


From v4.0, functions that access the browser APIs will provide an option fields for you to specify the global dependencies (e.g. `window`, `document` and `navigator`). It will use the global instance by default, so for most of the time, you don't need to worry about it. This configure is useful when working with iframes and testing environments.




```
// accessing parent context
const parentMousePos = useMouse({ window: window.parent })

const iframe = document.querySelect('#my-iframe')

// accessing child context
const childMousePos = useMouse({ window: iframe.contentWindow })
```




```
// testing
const mockWindow = { /* ... */ }

const { x, y } = useMouse({ window: mockWindow })
```



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/guide/config>

Guidelines
==========


Here are the guidelines for VueUse functions. You could also take them as a reference for authoring your own composable functions or apps.


You can also find some reasons for those design decisions and also some tips for writing composable functions with [Anthony Fu](https://github.com/antfu)'s talk about VueUse:


* [Composable Vue](https://antfu.me/posts/composable-vue-vueday-2021) - at VueDay 2021
* [可组合的 Vue](https://antfu.me/posts/composable-vue-vueconf-china-2021) - at VueConf China 2021 (in Chinese)


General
-------


* Import all Vue APIs from `"vue-demi"`
* Use `ref` instead of `reactive` whenever possible
* Use options object as arguments whenever possible to be more flexible for future extensions.
* Use `shallowRef` instead of `ref` when wrapping large amounts of data.
* Use `configurableWindow` (etc.) when using global variables like `window` to be flexible when working with multi-windows, testing mocks, and SSR.
* When involved with Web APIs that are not yet implemented by the browser widely, also outputs `isSupported` flag
* When using `watch` or `watchEffect` internally, also make the `immediate` and `flush` options configurable whenever possible
* Use [`tryOnUnmounted`](shared/tryonunmounted/index) to clear the side-effects gracefully
* Avoid using console logs
* When the function is asynchronous, return a PromiseLike


Read also: [Best Practice](guide/best-practice)


ShallowRef
----------


Use `shallowRef` instead of `ref` when wrapping large amounts of data.




```
export function useFetch<T>(url: MaybeRefOrGetter<string>) {
  // use `shallowRef` to prevent deep reactivity
  const data = shallowRef<T | undefined>()
  const error = shallowRef<Error | undefined>()

  fetch(toValue(url))
    .then(r => r.json())
    .then(r => data.value = r)
    .catch(e => error.value = e)

  /* ... */
}
```


Configurable Globals
--------------------


When using global variables like `window` or `document`, support `configurableWindow` or `configurableDocument` in the options interface to make the function flexible when for scenarios like multi-windows, testing mocks, and SSR.


Learn more about the implementation: [`_configurable.ts`](https://github.com/vueuse/vueuse/blob/main/packages/core/_configurable.ts)




```
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'

export function useActiveElement<T extends HTMLElement>(
  options: ConfigurableWindow = {},
) {
  const {
    // defaultWindow = isClient ? window : undefined
    window = defaultWindow,
  } = options

  let el: T

  // skip when in Node.js environment (SSR)
  if (window) {
    window.addEventListener('blur', () => {
      el = window?.document.activeElement
    }, true)
  }

  /* ... */
}
```


Usage example:




```
// in iframe and bind to the parent window
useActiveElement({ window: window.parent })
```


Watch Options
-------------


When using `watch` or `watchEffect` internally, also make the `immediate` and `flush` options configurable whenever possible. For example [`watchDebounced`](shared/watchdebounced/index)




```
import type { WatchOptions } from 'vue-demi'

// extend the watch options
export interface WatchDebouncedOptions extends WatchOptions {
  debounce?: number
}

export function watchDebounced(
  source: any,
  cb: any,
  options: WatchDebouncedOptions = {},
): WatchStopHandle {
  return watch(
    source,
    () => { /* ... */ },
    options, // pass watch options
  )
}
```


Controls
--------


We use the `controls` option allowing users to use functions with a single return for simple usages, while being able to have more controls and flexibility when needed. Read more: [#362](https://github.com/vueuse/vueuse/pull/362).


#### When to provide a `controls` option


* The function is more commonly used with single `ref` or
* Examples: [`useTimestamp`](core/usetimestamp/index) [`useInterval`](shared/useinterval/index)




```
// common usage
const timestamp = useTimestamp()

// more controls for flexibility
const { timestamp, pause, resume } = useTimestamp({ controls: true })
```


Refer to [`useTimestamp`](core/usetimestamp/index) s source code for the implementation of proper TypeScript support.


#### When **NOT** to provide a `controls` option


* The function is more commonly used with multiple returns
* Examples: [`useRafFn`](core/useraffn/index) [`useRefHistory`](core/userefhistory/index)




```
const { pause, resume } = useRafFn(() => {})
```



`isSupported` Flag
-------------------


When involved with Web APIs that are not yet implemented by the browser widely, also outputs `isSupported` flag.


For example [`useShare`](core/useshare/index)




```
export function useShare(
  shareOptions: MaybeRef<ShareOptions> = {},
  options: ConfigurableNavigator = {},
) {
  const { navigator = defaultNavigator } = options
  const isSupported = useSupported(() => navigator && 'canShare' in navigator)

  const share = async (overrideOptions) => {
    if (isSupported.value) {
      /* ...implementation */
    }
  }

  return {
    isSupported,
    share,
  }
}
```


Asynchronous Composables
------------------------


When a composable is asynchronous, like [`useFetch`](core/usefetch/index) it is a good idea to return a PromiseLike object from the composable so the user is able to await the function. This is especially useful in the case of Vue's `<Suspense>` api.


* Use a `ref` to determine when the function should resolve e.g. `isFinished`
* Store the return state in a variable as it must be returned twice, once in the return and once in the promise.
* The return type should be an intersection between the return type and a PromiseLike, e.g. `UseFetchReturn & PromiseLike<UseFetchReturn>`




```
export function useFetch<T>(url: MaybeRefOrGetter<string>): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>> {
  const data = shallowRef<T | undefined>()
  const error = shallowRef<Error | undefined>()
  const isFinished = ref(false)

  fetch(toValue(url))
    .then(r => r.json())
    .then(r => data.value = r)
    .catch(e => error.value = e)
    .finally(() => isFinished.value = true)

  // Store the return state in a variable
  const state: UseFetchReturn<T> = {
    data,
    error,
    isFinished,
  }

  return {
    ...state,
    // Adding `then` to an object allows it to be awaited.
    then(onFulfilled, onRejected) {
      return new Promise<UseFetchReturn<T>>((resolve, reject) => {
        until(isFinished)
          .toBeTruthy()
          .then(() => resolve(state))
          .then(() => reject(state))
      }).then(onFulfilled, onRejected)
    },
  }
}
```


Renderless Components
---------------------


* Use render functions instead of Vue SFC
* Wrap the props in `reactive` to easily pass them as props to the slot
* Prefer to use the functions options as prop types instead of recreating them yourself
* Only wrap the slot in an HTML element if the function needs a target to bind to




```
import { defineComponent, reactive } from 'vue-demi'
import type { MouseOptions } from '@vueuse/core'
import { useMouse } from '@vueuse/core'

export const UseMouse = defineComponent<MouseOptions>({
  name: 'UseMouse',
  props: ['touch', 'resetOnTouchEnds', 'initialValue'] as unknown as undefined,
  setup(props, { slots }) {
    const data = reactive(useMouse(props))

    return () => {
      if (slots.default)
        return slots.default(data)
    }
  },
})
```


Sometimes a function may have multiple parameters, in that case, you maybe need to create a new interface to merge all the interfaces into a single interface for the component props.




```
import type { TimeAgoOptions } from '@vueuse/core'
import { useTimeAgo } from '@vueuse/core'

interface UseTimeAgoComponentOptions extends Omit<TimeAgoOptions<true>, 'controls'> {
  time: MaybeRef<Date | number | string>
}

export const UseTimeAgo = defineComponent<UseTimeAgoComponentOptions>({ /* ... */ })
```



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/guidelines>

Export size
===========


generated by [export-size](https://github.com/antfu/export-size)  
 version: 10.0.0-beta.5  
 date: 2023-04-13T22:44:38.063Z



> Please note this is bundle size for each individual APIs (excluding Vue). Since we have a lot shared utilities underneath each function, importing two different functions does NOT necessarily mean the bundle size will be the sum of them (usually smaller). Depends on the bundler and minifier you use, the final result might vary, this list is for reference only.
> 
> 


`@vueuse/core`




| Function | min+gzipped |
| --- | --- |
| [`useDark`](core/usedark/index) | 3.03 kB |
| [`useColorMode`](core/usecolormode/index) | 2.88 kB |
| `createFetch` | 2.78 kB |
| [`useFetch`](core/usefetch/index) | 2.42 kB |
| [`useMediaControls`](core/usemediacontrols/index) | 2.36 kB |
| [`useSessionStorage`](core/usesessionstorage/index) | 2.02 kB |
| [`useLocalStorage`](core/uselocalstorage/index) | 2.01 kB |
| [`useStorage`](core/usestorage/index) | 1.99 kB |
| [`useInfiniteScroll`](core/useinfinitescroll/index) | 1.94 kB |
| [`useVirtualList`](core/usevirtuallist/index) | 1.8 kB |
| [`useThrottledRefHistory`](core/usethrottledrefhistory/index) | 1.73 kB |
| [`useDebouncedRefHistory`](core/usedebouncedrefhistory/index) | 1.7 kB |
| [`useStorageAsync`](core/usestorageasync/index) | 1.63 kB |
| [`useTimeAgo`](core/usetimeago/index) | 1.63 kB |
| [`useUrlSearchParams`](core/useurlsearchparams/index) | 1.59 kB |
| [`useAnimate`](core/useanimate/index) | 1.56 kB |
| [`useScroll`](core/usescroll/index) | 1.5 kB |
| [`useScreenSafeArea`](core/usescreensafearea/index) | 1.49 kB |
| [`useParallax`](core/useparallax/index) | 1.47 kB |
| [`useRefHistory`](core/userefhistory/index) | 1.46 kB |
| [`usePointerLock`](core/usepointerlock/index) | 1.36 kB |
| [`useDraggable`](core/usedraggable/index) | 1.35 kB |
| [`useWebSocket`](core/usewebsocket/index) | 1.34 kB |
| [`useGamepad`](core/usegamepad/index) | 1.25 kB |
| [`useElementBounding`](core/useelementbounding/index) | 1.15 kB |
| [`usePointer`](core/usepointer/index) | 1.14 kB |
| [`useTransition`](core/usetransition/index) | 1.14 kB |
| [`useDevicesList`](core/usedeviceslist/index) | 1.09 kB |
| [`useMouseInElement`](core/usemouseinelement/index) | 1.08 kB |
| [`usePointerSwipe`](core/usepointerswipe/index) | 1.04 kB |
| [`useClipboard`](core/useclipboard/index) | 1.02 kB |
| [`useMagicKeys`](core/usemagickeys/index) | 1.02 kB |
| [`useFullscreen`](core/usefullscreen/index) | 1.01 kB |
| [`useSwipe`](core/useswipe/index) | 983 B |
| [`useIdle`](core/useidle/index) | 977 B |
| [`useWebNotification`](core/usewebnotification/index) | 964 B |
| [`useWindowSize`](core/usewindowsize/index) | 964 B |
| [`useBrowserLocation`](core/usebrowserlocation/index) | 952 B |
| [`useElementSize`](core/useelementsize/index) | 950 B |
| [`useScrollLock`](core/usescrolllock/index) | 919 B |
| [`useBreakpoints`](core/usebreakpoints/index) | 915 B |
| `onKeyUp` | 908 B |
| `onKeyPressed` | 907 B |
| `onKeyDown` | 906 B |
| [`useTitle`](core/usetitle/index) | 905 B |
| [`onClickOutside`](core/onclickoutside/index) | 888 B |
| [`useFileSystemAccess`](core/usefilesystemaccess/index) | 878 B |
| [`useTextareaAutosize`](core/usetextareaautosize/index) | 857 B |
| [`useOnline`](core/useonline/index) | 830 B |
| [`useTextDirection`](core/usetextdirection/index) | 821 B |
| [`useTimestamp`](core/usetimestamp/index) | 817 B |
| [`useNetwork`](core/usenetwork/index) | 814 B |
| [`useCssVar`](core/usecssvar/index) | 806 B |
| [`useMouse`](core/usemouse/index) | 790 B |
| [`useNow`](core/usenow/index) | 788 B |
| `formatTimeAgo` | 774 B |
| [`useBase64`](core/usebase64/index) | 769 B |
| [`useFocusWithin`](core/usefocuswithin/index) | 769 B |
| [`usePermission`](core/usepermission/index) | 759 B |
| [`useImage`](core/useimage/index) | 757 B |
| [`useWebWorkerFn`](core/usewebworkerfn/index) | 749 B |
| [`useBattery`](core/usebattery/index) | 743 B |
| [`createReusableTemplate`](core/createreusabletemplate/index) | 734 B |
| [`useWakeLock`](core/usewakelock/index) | 727 B |
| [`useSpeechSynthesis`](core/usespeechsynthesis/index) | 724 B |
| [`useActiveElement`](core/useactiveelement/index) | 712 B |
| [`onStartTyping`](core/onstarttyping/index) | 704 B |
| [`useScreenOrientation`](core/usescreenorientation/index) | 704 B |
| [`useDeviceMotion`](core/usedevicemotion/index) | 703 B |
| [`useSpeechRecognition`](core/usespeechrecognition/index) | 694 B |
| [`useFileDialog`](core/usefiledialog/index) | 693 B |
| [`useTextSelection`](core/usetextselection/index) | 681 B |
| [`useEventSource`](core/useeventsource/index) | 679 B |
| [`useMousePressed`](core/usemousepressed/index) | 679 B |
| [`useScriptTag`](core/usescripttag/index) | 676 B |
| [`onLongPress`](core/onlongpress/index) | 675 B |
| [`useDeviceOrientation`](core/usedeviceorientation/index) | 672 B |
| [`useResizeObserver`](core/useresizeobserver/index) | 672 B |
| [`useVibrate`](core/usevibrate/index) | 671 B |
| [`onKeyStroke`](core/onkeystroke/index) | 651 B |
| [`useOffsetPagination`](core/useoffsetpagination/index) | 650 B |
| [`useElementByPoint`](core/useelementbypoint/index) | 642 B |
| [`useNavigatorLanguage`](core/usenavigatorlanguage/index) | 632 B |
| [`useDropZone`](core/usedropzone/index) | 629 B |
| [`useElementVisibility`](core/useelementvisibility/index) | 626 B |
| `executeTransition` | 616 B |
| [`useMutationObserver`](core/usemutationobserver/index) | 612 B |
| [`useFocus`](core/usefocus/index) | 605 B |
| [`useElementHover`](core/useelementhover/index) | 598 B |
| [`useBluetooth`](core/usebluetooth/index) | 596 B |
| [`useKeyModifier`](core/usekeymodifier/index) | 587 B |
| [`usePreferredContrast`](core/usepreferredcontrast/index) | 583 B |
| [`usePageLeave`](core/usepageleave/index) | 576 B |
| [`useIntersectionObserver`](core/useintersectionobserver/index) | 572 B |
| [`usePreferredColorScheme`](core/usepreferredcolorscheme/index) | 570 B |
| [`useUserMedia`](core/useusermedia/index) | 569 B |
| [`useVModels`](core/usevmodels/index) | 562 B |
| [`usePreferredReducedMotion`](core/usepreferredreducedmotion/index) | 557 B |
| [`useWindowScroll`](core/usewindowscroll/index) | 555 B |
| [`useShare`](core/useshare/index) | 546 B |
| [`useDocumentVisibility`](core/usedocumentvisibility/index) | 542 B |
| [`usePreferredLanguages`](core/usepreferredlanguages/index) | 537 B |
| [`usePerformanceObserver`](core/useperformanceobserver/index) | 536 B |
| [`usePreferredDark`](core/usepreferreddark/index) | 536 B |
| [`useVModel`](core/usevmodel/index) | 534 B |
| [`useWindowFocus`](core/usewindowfocus/index) | 532 B |
| [`useGeolocation`](core/usegeolocation/index) | 526 B |
| [`useMemory`](core/usememory/index) | 524 B |
| [`useManualRefHistory`](core/usemanualrefhistory/index) | 516 B |
| [`useMediaQuery`](core/usemediaquery/index) | 505 B |
| [`useCloned`](core/usecloned/index) | 499 B |
| [`createTemplatePromise`](core/createtemplatepromise/index) | 497 B |
| [`useParentElement`](core/useparentelement/index) | 496 B |
| [`useBroadcastChannel`](core/usebroadcastchannel/index) | 476 B |
| [`useDisplayMedia`](core/usedisplaymedia/index) | 476 B |
| [`useStyleTag`](core/usestyletag/index) | 474 B |
| [`useEventListener`](core/useeventlistener/index) | 467 B |
| [`useCycleList`](core/usecyclelist/index) | 458 B |
| [`useFps`](core/usefps/index) | 458 B |
| [`useStepper`](core/usestepper/index) | 433 B |
| [`useAsyncState`](core/useasyncstate/index) | 424 B |
| [`useConfirmDialog`](core/useconfirmdialog/index) | 418 B |
| [`useTimeoutPoll`](core/usetimeoutpoll/index) | 407 B |
| [`useMemoize`](core/usememoize/index) | 403 B |
| [`useAsyncQueue`](core/useasyncqueue/index) | 391 B |
| [`useSorted`](core/usesorted/index) | 366 B |
| `TransitionPresets` | 363 B |
| [`useFavicon`](core/usefavicon/index) | 362 B |
| `asyncComputed` | 358 B |
| `computedAsync` | 358 B |
| [`useCurrentElement`](core/usecurrentelement/index) | 355 B |
| [`useRafFn`](core/useraffn/index) | 342 B |
| [`useEventBus`](core/useeventbus/index) | 332 B |
| [`useWebWorker`](core/usewebworker/index) | 322 B |
| [`useEyeDropper`](core/useeyedropper/index) | 314 B |
| `mapGamepadToXbox360Controller` | 304 B |
| [`useDevicePixelRatio`](core/usedevicepixelratio/index) | 294 B |
| [`useObjectUrl`](core/useobjecturl/index) | 278 B |
| [`templateRef`](core/templateref/index) | 270 B |
| [`usePrevious`](core/useprevious/index) | 260 B |
| `StorageSerializers` | 246 B |
| `setSSRHandler` | 240 B |
| `getSSRHandler` | 213 B |
| [`useSupported`](core/usesupported/index) | 194 B |
| [`computedInject`](core/computedinject/index) | 183 B |
| `breakpointsMasterCss` | 178 B |
| [`useTemplateRefsList`](core/usetemplaterefslist/index) | 177 B |
| [`useCached`](core/usecached/index) | 169 B |
| `DefaultMagicKeysAliasMap` | 166 B |
| [`createUnrefFn`](core/createunreffn/index) | 166 B |
| [`unrefElement`](core/unrefelement/index) | 165 B |
| `breakpointsSematic` | 158 B |
| [`useMounted`](core/usemounted/index) | 156 B |
| `breakpointsBootstrapV5` | 145 B |
| `breakpointsTailwind` | 145 B |
| `breakpointsAntDesign` | 141 B |
| `breakpointsQuasar` | 129 B |
| `breakpointsVuetify` | 124 B |
| `cloneFnJSON` | 122 B |
| `customStorageEventName` | 111 B |
| `defaultNavigator` | 108 B |
| `defaultWindow` | 104 B |
| `defaultDocument` | 101 B |
| `defaultLocation` | 100 B |


`@vueuse/components`




| Function | min+gzipped |
| --- | --- |
| `UseColorMode` | 5.98 kB |
| `UseScreenSafeArea` | 4.59 kB |
| `UseImage` | 4.54 kB |
| `UseDraggable` | 4.37 kB |
| `UseOffsetPagination` | 4.29 kB |
| `UseVirtualList` | 4.28 kB |
| `UseDark` | 4.25 kB |
| `UseTimeAgo` | 4.21 kB |
| `UsePointer` | 4.2 kB |
| `UseMousePressed` | 4.2 kB |
| `UseTimestamp` | 4.18 kB |
| `UseElementSize` | 4.17 kB |
| `UseNow` | 4.17 kB |
| `OnClickOutside` | 4.16 kB |
| `UseMouseInElement` | 4.16 kB |
| `OnLongPress` | 4.15 kB |
| `UseElementVisibility` | 4.15 kB |
| `UseElementBounding` | 4.15 kB |
| `UseIdle` | 4.15 kB |
| `vScroll` | 4.14 kB |
| `UseGeolocation` | 4.14 kB |
| `UseMouse` | 4.14 kB |
| `UseDevicesList` | 4.14 kB |
| `UsePointerLock` | 4.14 kB |
| `UseFullscreen` | 4.14 kB |
| `VOnClickOutside` | 4.14 kB |
| `vOnClickOutside` | 4.14 kB |
| `vOnKeyStroke` | 4.13 kB |
| `UsePreferredColorScheme` | 4.13 kB |
| `UseObjectUrl` | 4.13 kB |
| `UseEyeDropper` | 4.13 kB |
| `UseWindowSize` | 4.13 kB |
| `vElementSize` | 4.13 kB |
| `UsePreferredDark` | 4.13 kB |
| `UsePreferredReducedMotion` | 4.13 kB |
| `UsePageLeave` | 4.12 kB |
| `UsePreferredLanguages` | 4.12 kB |
| `UsePreferredContrast` | 4.12 kB |
| `UseDocumentVisibility` | 4.12 kB |
| `UseWindowFocus` | 4.12 kB |
| `UseDeviceOrientation` | 4.12 kB |
| `UseDevicePixelRatio` | 4.12 kB |
| `UseActiveElement` | 4.12 kB |
| `UseDeviceMotion` | 4.11 kB |
| `UseOnline` | 4.11 kB |
| `UseNetwork` | 4.11 kB |
| `UseBattery` | 4.11 kB |
| `UseBrowserLocation` | 4.11 kB |
| `vElementVisibility` | 4.11 kB |
| `VOnLongPress` | 4.09 kB |
| `vOnLongPress` | 4.09 kB |
| `vIntersectionObserver` | 4.09 kB |
| `vInfiniteScroll` | 4.08 kB |
| `vElementHover` | 4.08 kB |
| `vScrollLock` | 4.05 kB |


`@vueuse/math`




| Function | min+gzipped |
| --- | --- |
| [`useClamp`](math/useclamp/index) | 214 B |
| [`useMath`](math/usemath/index) | 198 B |
| [`useProjection`](math/useprojection/index) | 196 B |
| [`useAverage`](math/useaverage/index) | 195 B |
| [`useSum`](math/usesum/index) | 194 B |
| [`createProjection`](math/createprojection/index) | 193 B |
| [`useMin`](math/usemin/index) | 191 B |
| [`useMax`](math/usemax/index) | 190 B |
| [`usePrecision`](math/useprecision/index) | 175 B |
| [`createGenericProjection`](math/creategenericprojection/index) | 132 B |
| `and` | 123 B |
| [`logicAnd`](math/logicand/index) | 123 B |
| [`logicOr`](math/logicor/index) | 122 B |
| `or` | 122 B |
| [`useTrunc`](math/usetrunc/index) | 120 B |
| [`useAbs`](math/useabs/index) | 115 B |
| [`useCeil`](math/useceil/index) | 115 B |
| [`useRound`](math/useround/index) | 115 B |
| [`useFloor`](math/usefloor/index) | 114 B |
| [`logicNot`](math/logicnot/index) | 109 B |
| `not` | 109 B |


`@vueuse/nuxt`




| Function | min+gzipped |
| --- | --- |
| `default` | 778 B |


`@vueuse/router`




| Function | min+gzipped |
| --- | --- |
| [`useRouteQuery`](router/useroutequery/index) | 506 B |
| [`useRouteParams`](router/userouteparams/index) | 473 B |
| [`useRouteHash`](router/useroutehash/index) | 442 B |


`@vueuse/integrations`




| Function | min+gzipped |
| --- | --- |
| [`useAxios`](integrations/useaxios/index) | 1.54 kB |
| [`useAsyncValidator`](integrations/useasyncvalidator/index) | 1.34 kB |
| [`useDrauu`](integrations/usedrauu/index) | 924 B |
| `createCookies` | 727 B |
| [`useFocusTrap`](integrations/usefocustrap/index) | 718 B |
| [`useSortable`](integrations/usesortable/index) | 692 B |
| [`useCookies`](integrations/usecookies/index) | 691 B |
| [`useIDBKeyval`](integrations/useidbkeyval/index) | 675 B |
| [`useFuse`](integrations/usefuse/index) | 445 B |
| [`useNProgress`](integrations/usenprogress/index) | 425 B |
| [`useChangeCase`](integrations/usechangecase/index) | 385 B |
| [`useQRCode`](integrations/useqrcode/index) | 371 B |
| [`useJwt`](integrations/usejwt/index) | 313 B |
| `moveArrayElement` | 238 B |


`@vueuse/rxjs`




| Function | min+gzipped |
| --- | --- |
| [`useSubject`](rxjs/usesubject/index) | 235 B |
| `fromEvent` | 217 B |
| [`useObservable`](rxjs/useobservable/index) | 212 B |
| [`from`](rxjs/from/index) | 153 B |
| [`useSubscription`](rxjs/usesubscription/index) | 144 B |
| [`toObserver`](rxjs/toobserver/index) | 88 B |


`@vueuse/firebase`




| Function | min+gzipped |
| --- | --- |
| [`useFirestore`](firebase/usefirestore/index) | 631 B |
| [`useRTDB`](firebase/usertdb/index) | 210 B |
| [`useAuth`](firebase/useauth/index) | 164 B |


`@vueuse/electron`




| Function | min+gzipped |
| --- | --- |
| [`useIpcRenderer`](electron/useipcrenderer/index) | 460 B |
| [`useZoomFactor`](electron/usezoomfactor/index) | 317 B |
| [`useZoomLevel`](electron/usezoomlevel/index) | 281 B |
| [`useIpcRendererOn`](electron/useipcrendereron/index) | 242 B |
| [`useIpcRendererInvoke`](electron/useipcrendererinvoke/index) | 218 B |


`@vueuse/shared`




| Function | min+gzipped |
| --- | --- |
| [`watchTriggerable`](shared/watchtriggerable/index) | 942 B |
| `throttledWatch` | 831 B |
| [`watchThrottled`](shared/watchthrottled/index) | 831 B |
| `debouncedWatch` | 786 B |
| [`watchDebounced`](shared/watchdebounced/index) | 786 B |
| [`useDateFormat`](shared/usedateformat/index) | 779 B |
| `ignorableWatch` | 708 B |
| [`watchIgnorable`](shared/watchignorable/index) | 708 B |
| `pausableWatch` | 674 B |
| [`watchPausable`](shared/watchpausable/index) | 674 B |
| [`useInterval`](shared/useinterval/index) | 620 B |
| [`until`](shared/until/index) | 595 B |
| [`useTimeout`](shared/usetimeout/index) | 565 B |
| `formatDate` | 514 B |
| [`watchAtMost`](shared/watchatmost/index) | 510 B |
| `controlledRef` | 489 B |
| [`refWithControl`](shared/refwithcontrol/index) | 474 B |
| [`refThrottled`](shared/refthrottled/index) | 458 B |
| `throttledRef` | 458 B |
| `useThrottle` | 458 B |
| [`reactivePick`](shared/reactivepick/index) | 454 B |
| [`toRefs`](shared/torefs/index) | 451 B |
| `debouncedRef` | 423 B |
| [`refDebounced`](shared/refdebounced/index) | 423 B |
| `useDebounce` | 423 B |
| [`useThrottleFn`](shared/usethrottlefn/index) | 401 B |
| [`computedEager`](shared/computedeager/index) | 398 B |
| `eagerComputed` | 398 B |
| [`reactiveOmit`](shared/reactiveomit/index) | 381 B |
| [`watchWithFilter`](shared/watchwithfilter/index) | 373 B |
| [`useDebounceFn`](shared/usedebouncefn/index) | 372 B |
| [`makeDestructurable`](shared/makedestructurable/index) | 364 B |
| [`useArrayIncludes`](shared/usearrayincludes/index) | 348 B |
| [`useIntervalFn`](shared/useintervalfn/index) | 341 B |
| [`watchDeep`](shared/watchdeep/index) | 325 B |
| [`watchImmediate`](shared/watchimmediate/index) | 322 B |
| [`reactifyObject`](shared/reactifyobject/index) | 305 B |
| [`useTimeoutFn`](shared/usetimeoutfn/index) | 303 B |
| `throttleFilter` | 289 B |
| [`extendRef`](shared/extendref/index) | 282 B |
| [`watchArray`](shared/watcharray/index) | 281 B |
| `debounceFilter` | 277 B |
| [`reactiveComputed`](shared/reactivecomputed/index) | 264 B |
| `normalizeDate` | 261 B |
| [`computedWithControl`](shared/computedwithcontrol/index) | 250 B |
| `controlledComputed` | 250 B |
| [`toReactive`](shared/toreactive/index) | 242 B |
| [`syncRef`](shared/syncref/index) | 237 B |
| `autoResetRef` | 234 B |
| [`refAutoReset`](shared/refautoreset/index) | 234 B |
| [`useArrayDifference`](shared/usearraydifference/index) | 231 B |
| [`useArrayUnique`](shared/usearrayunique/index) | 215 B |
| [`createSharedComposable`](shared/createsharedcomposable/index) | 213 B |
| [`createEventHook`](shared/createeventhook/index) | 212 B |
| [`useToNumber`](shared/usetonumber/index) | 200 B |
| [`useToggle`](shared/usetoggle/index) | 200 B |
| [`useArrayFindLast`](shared/usearrayfindlast/index) | 191 B |
| [`useCounter`](shared/usecounter/index) | 185 B |
| `createReactiveFn` | 174 B |
| [`reactify`](shared/reactify/index) | 174 B |
| [`useArrayReduce`](shared/usearrayreduce/index) | 171 B |
| `increaseWithUnit` | 169 B |
| `resolveRef` | 169 B |
| `pausableFilter` | 165 B |
| [`toRef`](shared/toref/index) | 159 B |
| [`syncRefs`](shared/syncrefs/index) | 158 B |
| `isIOS` | 146 B |
| [`useLastChanged`](shared/uselastchanged/index) | 143 B |
| [`set`](shared/set/index) | 142 B |
| `createFilterWrapper` | 139 B |
| `directiveHooks` | 139 B |
| [`useArrayEvery`](shared/usearrayevery/index) | 137 B |
| [`useArrayFind`](shared/usearrayfind/index) | 137 B |
| [`useArrayJoin`](shared/usearrayjoin/index) | 137 B |
| [`useArraySome`](shared/usearraysome/index) | 137 B |
| [`useArrayFindIndex`](shared/usearrayfindindex/index) | 136 B |
| [`useArrayMap`](shared/usearraymap/index) | 133 B |
| [`createInjectionState`](shared/createinjectionstate/index) | 132 B |
| [`useArrayFilter`](shared/usearrayfilter/index) | 132 B |
| [`createGlobalState`](shared/createglobalstate/index) | 125 B |
| `createSingletonPromise` | 122 B |
| `objectPick` | 117 B |
| `objectOmit` | 115 B |
| [`tryOnBeforeMount`](shared/tryonbeforemount/index) | 114 B |
| [`useToString`](shared/usetostring/index) | 111 B |
| [`tryOnMounted`](shared/tryonmounted/index) | 109 B |
| [`refDefault`](shared/refdefault/index) | 107 B |
| [`watchOnce`](shared/watchonce/index) | 107 B |
| `promiseTimeout` | 105 B |
| [`tryOnScopeDispose`](shared/tryonscopedispose/index) | 100 B |
| `resolveUnref` | 99 B |
| `whenever` | 97 B |
| `rand` | 95 B |
| [`tryOnBeforeUnmount`](shared/tryonbeforeunmount/index) | 93 B |
| [`toValue`](shared/tovalue/index) | 92 B |
| `isObject` | 89 B |
| `clamp` | 87 B |
| [`isDefined`](shared/isdefined/index) | 86 B |
| [`tryOnUnmounted`](shared/tryonunmounted/index) | 85 B |
| `hasOwn` | 83 B |
| `containsProp` | 80 B |
| [`get`](shared/get/index) | 80 B |
| `assert` | 78 B |
| `bypassFilter` | 69 B |
| `isClient` | 68 B |
| `identity` | 66 B |
| `objectEntries` | 65 B |
| `timestamp` | 65 B |
| `invoke` | 63 B |
| `isDef` | 62 B |
| `now` | 61 B |
| `noop` | 56 B |



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/export-size>

Functions
=========




|  |  |
| --- | --- |
|  Core  | StateElementsBrowserSensorsNetworkAnimationComponentWatchReactivityArrayTimeUtilities |
|  Add-ons  | ElectronFirebaseHeadIntegrationsMathMotionRouterRxJSSchemaOrgSound |
|  Sort by  | categorynameupdated |
|  Filters  | Has ComponentHas Directive |






### State



[createGlobalState](shared/createglobalstate/index)-keep states in the global scope to be reusable across Vue instances


[createInjectionState](shared/createinjectionstate/index)-create global state that can be injected into components


[createSharedComposable](shared/createsharedcomposable/index)-make a composable function usable with multiple Vue instances


[useAsyncState](core/useasyncstate/index)-reactive async state


[useDebouncedRefHistory](core/usedebouncedrefhistory/index)-shorthand for `useRefHistory` with debounced filter


[useLastChanged](shared/uselastchanged/index)-records the timestamp of the last change


[useLocalStorage](core/uselocalstorage/index)-reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)


[useManualRefHistory](core/usemanualrefhistory/index)-manually track the change history of a ref when the using calls `commit()`


[useRefHistory](core/userefhistory/index)-track the change history of a ref


[useSessionStorage](core/usesessionstorage/index)-reactive [SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)


[useStorage](core/usestorage/index)-reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)/[SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)


[useStorageAsync](core/usestorageasync/index)-reactive Storage in with async support


[useThrottledRefHistory](core/usethrottledrefhistory/index)-shorthand for `useRefHistory` with throttled filter

### Elements



[useActiveElement](core/useactiveelement/index)-reactive `document.activeElement`


[useDocumentVisibility](core/usedocumentvisibility/index)-reactively track [`document.visibilityState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState)


[useDraggable](core/usedraggable/index)-make elements draggable


[useDropZone](core/usedropzone/index)-create a zone where files can be dropped


[useElementBounding](core/useelementbounding/index)-reactive [bounding box](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of an HTML element


[useElementSize](core/useelementsize/index)-reactive size of an HTML element


[useElementVisibility](core/useelementvisibility/index)-tracks the visibility of an element within the viewport


[useIntersectionObserver](core/useintersectionobserver/index)-detects that a target element's visibility


[useMouseInElement](core/usemouseinelement/index)-reactive mouse position related to an element


[useMutationObserver](core/usemutationobserver/index)-watch for changes being made to the DOM tree


[useParentElement](core/useparentelement/index)-get parent element of the given element


[useResizeObserver](core/useresizeobserver/index)-reports changes to the dimensions of an Element's content or the border-box


[useWindowFocus](core/usewindowfocus/index)-reactively track window focus with `window.onfocus` and `window.onblur` events


[useWindowScroll](core/usewindowscroll/index)-reactive window scroll


[useWindowSize](core/usewindowsize/index)-reactive window size

### Browser



[useBluetooth](core/usebluetooth/index)-reactive [Web Bluetooth API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API)


[useBreakpoints](core/usebreakpoints/index)-reactive viewport breakpoints


[useBroadcastChannel](core/usebroadcastchannel/index)-reactive [BroadcastChannel API](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel)


[useBrowserLocation](core/usebrowserlocation/index)-reactive browser location


[useClipboard](core/useclipboard/index)-reactive [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API)


[useColorMode](core/usecolormode/index)-reactive color mode (dark / light / customs) with auto data persistence


[useCssVar](core/usecssvar/index)-manipulate CSS variables


[useDark](core/usedark/index)-reactive dark mode with auto data persistence


[useEventListener](core/useeventlistener/index)-use EventListener with ease


[useEyeDropper](core/useeyedropper/index)-reactive [EyeDropper API](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API)


[useFavicon](core/usefavicon/index)-reactive favicon


[useFileDialog](core/usefiledialog/index)-open file dialog with ease


[useFileSystemAccess](core/usefilesystemaccess/index)-create and read and write local files with [FileSystemAccessAPI](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API)


[useFullscreen](core/usefullscreen/index)-reactive [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API)


[useGamepad](core/usegamepad/index)-provides reactive bindings for the [Gamepad API](https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API)


[useImage](core/useimage/index)-reactive load an image in the browser


[useMediaControls](core/usemediacontrols/index)-reactive media controls for both `audio` and `video` elements


[useMediaQuery](core/usemediaquery/index)-reactive [Media Query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries)


[useMemory](core/usememory/index)-reactive Memory Info


[useObjectUrl](core/useobjecturl/index)-reactive URL representing an object


[usePerformanceObserver](core/useperformanceobserver/index)-observe performance metrics


[usePermission](core/usepermission/index)-reactive [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API)


[usePreferredColorScheme](core/usepreferredcolorscheme/index)-reactive [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) media query


[usePreferredContrast](core/usepreferredcontrast/index)-reactive [prefers-contrast](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-contrast) media query


[usePreferredDark](core/usepreferreddark/index)-reactive dark theme preference


[usePreferredLanguages](core/usepreferredlanguages/index)-reactive [Navigator Languages](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages)


[usePreferredReducedMotion](core/usepreferredreducedmotion/index)-reactive [prefers-reduced-motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion) media query


[useScreenOrientation](core/usescreenorientation/index)-reactive [Screen Orientation API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API)


[useScreenSafeArea](core/usescreensafearea/index)-reactive `env(safe-area-inset-*)`


[useScriptTag](core/usescripttag/index)-script tag injecting


[useShare](core/useshare/index)-reactive [Web Share API](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share)


[useStyleTag](core/usestyletag/index)-inject reactive `style` element in head


[useTextareaAutosize](core/usetextareaautosize/index)-automatically update the height of a textarea depending on the content


[useTextDirection](core/usetextdirection/index)-reactive [dir](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir) of the element's text


[useTitle](core/usetitle/index)-reactive document title


[useUrlSearchParams](core/useurlsearchparams/index)-reactive [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)


[useVibrate](core/usevibrate/index)-reactive [Vibration API](https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API)


[useWakeLock](core/usewakelock/index)-reactive [Screen Wake Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API)


[useWebNotification](core/usewebnotification/index)-reactive [Notification](https://developer.mozilla.org/en-US/docs/Web/API/notification)


[useWebWorker](core/usewebworker/index)-simple [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) registration and communication


[useWebWorkerFn](core/usewebworkerfn/index)-run expensive functions without blocking the UI

### Sensors



[onClickOutside](core/onclickoutside/index)-listen for clicks outside of an element


[onKeyStroke](core/onkeystroke/index)-listen for keyboard key being stroked


[onLongPress](core/onlongpress/index)-listen for a long press on an element


[onStartTyping](core/onstarttyping/index)-fires when users start typing on non-editable elements


[useBattery](core/usebattery/index)-reactive [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API)


[useDeviceMotion](core/usedevicemotion/index)-reactive [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent)


[useDeviceOrientation](core/usedeviceorientation/index)-reactive [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent)


[useDevicePixelRatio](core/usedevicepixelratio/index)-reactively track [`window.devicePixelRatio`](https://developer.mozilla.org/ru/docs/Web/API/Window/devicePixelRatio)


[useDevicesList](core/usedeviceslist/index)-reactive [enumerateDevices](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices) listing available input/output devices


[useDisplayMedia](core/usedisplaymedia/index)-reactive [`mediaDevices.getDisplayMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia) streaming


[useElementByPoint](core/useelementbypoint/index)-reactive element by point


[useElementHover](core/useelementhover/index)-reactive element's hover state


[useFocus](core/usefocus/index)-reactive utility to track or set the focus state of a DOM element


[useFocusWithin](core/usefocuswithin/index)-reactive utility to track if an element or one of its decendants has focus


[useFps](core/usefps/index)-reactive FPS (frames per second)


[useGeolocation](core/usegeolocation/index)-reactive [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API)


[useIdle](core/useidle/index)-tracks whether the user is being inactive


[useInfiniteScroll](core/useinfinitescroll/index)-infinite scrolling of the element


[useKeyModifier](core/usekeymodifier/index)-reactive [Modifier State](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState)


[useMagicKeys](core/usemagickeys/index)-reactive keys pressed state


[useMouse](core/usemouse/index)-reactive mouse position


[useMousePressed](core/usemousepressed/index)-reactive mouse pressing state


[useNavigatorLanguage](core/usenavigatorlanguage/index)-reactive [navigator.language](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language)


[useNetwork](core/usenetwork/index)-reactive [Network status](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API)


[useOnline](core/useonline/index)-reactive online state


[usePageLeave](core/usepageleave/index)-reactive state to show whether the mouse leaves the page


[useParallax](core/useparallax/index)-create parallax effect easily


[usePointer](core/usepointer/index)-reactive [pointer state](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events)


[usePointerLock](core/usepointerlock/index)-reactive [pointer lock](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API)


[usePointerSwipe](core/usepointerswipe/index)-reactive swipe detection based on [PointerEvents](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent)


[useScroll](core/usescroll/index)-reactive scroll position and state


[useScrollLock](core/usescrolllock/index)-lock scrolling of the element


[useSpeechRecognition](core/usespeechrecognition/index)-reactive [SpeechRecognition](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition)


[useSpeechSynthesis](core/usespeechsynthesis/index)-reactive [SpeechSynthesis](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis)


[useSwipe](core/useswipe/index)-reactive swipe detection based on [`TouchEvents`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent)


[useTextSelection](core/usetextselection/index)-reactively track user text selection based on [`Window.getSelection`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection)


[useUserMedia](core/useusermedia/index)-reactive [`mediaDevices.getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) streaming

### Network



[useEventSource](core/useeventsource/index)-an [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or [Server-Sent-Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) instance opens a persistent connection to an HTTP server


[useFetch](core/usefetch/index)-reactive [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provides the ability to abort requests


[useWebSocket](core/usewebsocket/index)-reactive [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket) client

### Animation



[useAnimate](core/useanimate/index)-reactive [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API)


[useInterval](shared/useinterval/index)-reactive counter increases on every interval


[useIntervalFn](shared/useintervalfn/index)-wrapper for `setInterval` with controls


[useNow](core/usenow/index)-reactive current Date instance


[useRafFn](core/useraffn/index)-call function on every `requestAnimationFrame`


[useTimeout](shared/usetimeout/index)-update value after a given time with controls


[useTimeoutFn](shared/usetimeoutfn/index)-wrapper for `setTimeout` with controls


[useTimestamp](core/usetimestamp/index)-reactive current timestamp


[useTransition](core/usetransition/index)-transition between values

### Component



[computedInject](core/computedinject/index)-combine computed and inject


[createReusableTemplate](core/createreusabletemplate/index)-define and reuse template inside the component scope


[createTemplatePromise](core/createtemplatepromise/index)-template as Promise


[templateRef](core/templateref/index)-shorthand for binding ref to template element


[tryOnBeforeMount](shared/tryonbeforemount/index)-safe `onBeforeMount`


[tryOnBeforeUnmount](shared/tryonbeforeunmount/index)-safe `onBeforeUnmount`


[tryOnMounted](shared/tryonmounted/index)-safe `onMounted`


[tryOnScopeDispose](shared/tryonscopedispose/index)-safe `onScopeDispose`


[tryOnUnmounted](shared/tryonunmounted/index)-safe `onUnmounted`


[unrefElement](core/unrefelement/index)-unref for dom element


[useCurrentElement](core/usecurrentelement/index)-get the DOM element of current component as a ref


[useMounted](core/usemounted/index)-mounted state in ref


[useTemplateRefsList](core/usetemplaterefslist/index)-shorthand for binding refs to template elements and components inside `v-for`


[useVirtualList](core/usevirtuallist/index)-::: warning


[useVModel](core/usevmodel/index)-shorthand for v-model binding


[useVModels](core/usevmodels/index)-shorthand for props v-model binding

### Watch



[until](shared/until/index)-promised one-time watch for changes


[watchArray](shared/watcharray/index)-watch for an array with additions and removals


[watchAtMost](shared/watchatmost/index)-`watch` with the number of times triggered


[watchDebounced](shared/watchdebounced/index)-debounced watch


[watchDeep](shared/watchdeep/index)-shorthand for watching value with {deep: true}


[watchIgnorable](shared/watchignorable/index)-ignorable watch


[watchImmediate](shared/watchimmediate/index)-shorthand for watching value with {immediate: true}


[watchOnce](shared/watchonce/index)-`watch` that only triggers once


[watchPausable](shared/watchpausable/index)-pausable watch


[watchThrottled](shared/watchthrottled/index)-throttled watch


[watchTriggerable](shared/watchtriggerable/index)-watch that can be triggered manually


[watchWithFilter](shared/watchwithfilter/index)-`watch` with additional EventFilter control


[whenever](shared/whenever/index)-shorthand for watching value to be truthy

### Reactivity



[computedAsync](core/computedasync/index)-computed for async functions


[computedEager](shared/computedeager/index)-eager computed without lazy evaluation


[computedWithControl](shared/computedwithcontrol/index)-explicitly define the dependencies of computed


[extendRef](shared/extendref/index)-add extra attributes to Ref


[reactify](shared/reactify/index)-converts plain functions into reactive functions


[reactifyObject](shared/reactifyobject/index)-apply `reactify` to an object


[reactiveComputed](shared/reactivecomputed/index)-computed reactive object


[reactiveOmit](shared/reactiveomit/index)-reactively omit fields from a reactive object


[reactivePick](shared/reactivepick/index)-reactively pick fields from a reactive object


[refAutoReset](shared/refautoreset/index)-a ref which will be reset to the default value after some time


[refDebounced](shared/refdebounced/index)-debounce execution of a ref value


[refDefault](shared/refdefault/index)-apply default value to a ref


[refThrottled](shared/refthrottled/index)-throttle changing of a ref value


[refWithControl](shared/refwithcontrol/index)-fine-grained controls over ref and its reactivity


[syncRef](shared/syncref/index)-two-way refs synchronization


[syncRefs](shared/syncrefs/index)-keep target refs in sync with a source ref


[toReactive](shared/toreactive/index)-converts ref to reactive


[toRef](shared/toref/index)-normalize value/ref/getter to `ref` or `computed`


[toRefs](shared/torefs/index)-extended [`toRefs`](https://v3.vuejs.org/api/refs-api.html#torefs) that also accepts refs of an object


[toValue](shared/tovalue/index)-get the value of value/ref/getter

### Array



[useArrayDifference](shared/usearraydifference/index)-reactive get array difference of two array


[useArrayEvery](shared/usearrayevery/index)-reactive `Array.every`


[useArrayFilter](shared/usearrayfilter/index)-reactive `Array.filter`


[useArrayFind](shared/usearrayfind/index)-reactive `Array.find`


[useArrayFindIndex](shared/usearrayfindindex/index)-reactive `Array.findIndex`


[useArrayFindLast](shared/usearrayfindlast/index)-reactive `Array.findLast`


[useArrayIncludes](shared/usearrayincludes/index)-reactive `Array.includes`


[useArrayJoin](shared/usearrayjoin/index)-reactive `Array.join`


[useArrayMap](shared/usearraymap/index)-reactive `Array.map`


[useArrayReduce](shared/usearrayreduce/index)-reactive `Array.reduce`


[useArraySome](shared/usearraysome/index)-reactive `Array.some`


[useArrayUnique](shared/usearrayunique/index)-reactive unique array


[useSorted](core/usesorted/index)-reactive sort array

### Time



[useDateFormat](shared/usedateformat/index)-get the formatted date according to the string of tokens passed in


[useTimeAgo](core/usetimeago/index)-reactive time ago

### Utilities



[createEventHook](shared/createeventhook/index)-utility for creating event hooks


[createUnrefFn](core/createunreffn/index)-make a plain function accepting ref and raw values as arguments


[get](shared/get/index)-shorthand for accessing `ref.value`


[isDefined](shared/isdefined/index)-non-nullish checking type guard for Ref


[makeDestructurable](shared/makedestructurable/index)-make isomorphic destructurable for object and array at the same time


[set](shared/set/index)-shorthand for `ref.value = x`


[useAsyncQueue](core/useasyncqueue/index)-executes each asynchronous task sequentially and passes the current task result to the next task


[useBase64](core/usebase64/index)-reactive base64 transforming


[useCached](core/usecached/index)-cache a ref with a custom comparator


[useCloned](core/usecloned/index)-reactive clone of a ref


[useConfirmDialog](core/useconfirmdialog/index)-creates event hooks to support modals and confirmation dialog chains


[useCounter](shared/usecounter/index)-basic counter with utility functions


[useCycleList](core/usecyclelist/index)-cycle through a list of items


[useDebounceFn](shared/usedebouncefn/index)-debounce execution of a function


[useEventBus](core/useeventbus/index)-a basic event bus


[useMemoize](core/usememoize/index)-cache results of functions depending on arguments and keep it reactive


[useOffsetPagination](core/useoffsetpagination/index)-reactive offset pagination


[usePrevious](core/useprevious/index)-holds the previous value of a ref


[useStepper](core/usestepper/index)-provides helpers for building a multi-step wizard interface


[useSupported](core/usesupported/index)-sSR compatibility `isSupported`


[useThrottleFn](shared/usethrottlefn/index)-throttle execution of a function


[useTimeoutPoll](core/usetimeoutpoll/index)-use timeout to poll something


[useToggle](shared/usetoggle/index)-a boolean switcher with utility functions


[useToNumber](shared/usetonumber/index)-reactively convert a string ref to number


[useToString](shared/usetostring/index)-reactively convert a ref to string

### @Electron



[useIpcRenderer](electron/useipcrenderer/index)-provides [ipcRenderer](https://www.electronjs.org/docs/api/ipc-renderer) and all of its APIs


[useIpcRendererInvoke](electron/useipcrendererinvoke/index)-reactive [ipcRenderer.invoke API](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererinvokechannel-args) result


[useIpcRendererOn](electron/useipcrendereron/index)-use [ipcRenderer.on](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendereronchannel-listener) with ease and [ipcRenderer.removeListener](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovelistenerchannel-listener) automatically on unmounted


[useZoomFactor](electron/usezoomfactor/index)-reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom factor


[useZoomLevel](electron/usezoomlevel/index)-reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom level

### @Firebase



[useAuth](firebase/useauth/index)-reactive [Firebase Auth](https://firebase.google.com/docs/auth) binding


[useFirestore](firebase/usefirestore/index)-reactive [Firestore](https://firebase.google.com/docs/firestore) binding


[useRTDB](firebase/usertdb/index)-reactive [Firebase Realtime Database](https://firebase.google.com/docs/database) binding

### @Head



[createHead](https://github.com/vueuse/head#api)-create the head manager instance.


[useHead](https://github.com/vueuse/head#api)-update head meta tags reactively.

### @Integrations



[useAsyncValidator](integrations/useasyncvalidator/index)-wrapper for [`async-validator`](https://github.com/yiminghe/async-validator)


[useAxios](integrations/useaxios/index)-wrapper for [`axios`](https://github.com/axios/axios)


[useChangeCase](integrations/usechangecase/index)-reactive wrapper for [`change-case`](https://github.com/blakeembrey/change-case)


[useCookies](integrations/usecookies/index)-wrapper for [`universal-cookie`](https://www.npmjs.com/package/universal-cookie)


[useDrauu](integrations/usedrauu/index)-reactive instance for [drauu](https://github.com/antfu/drauu)


[useFocusTrap](integrations/usefocustrap/index)-reactive wrapper for [`focus-trap`](https://github.com/focus-trap/focus-trap)


[useFuse](integrations/usefuse/index)-easily implement fuzzy search using a composable with [Fuse.js](https://github.com/krisk/fuse)


[useIDBKeyval](integrations/useidbkeyval/index)-wrapper for [`idb-keyval`](https://www.npmjs.com/package/idb-keyval)


[useJwt](integrations/usejwt/index)-wrapper for [`jwt-decode`](https://github.com/auth0/jwt-decode)


[useNProgress](integrations/usenprogress/index)-reactive wrapper for [`nprogress`](https://github.com/rstacruz/nprogress)


[useQRCode](integrations/useqrcode/index)-wrapper for [`qrcode`](https://github.com/soldair/node-qrcode)


[useSortable](integrations/usesortable/index)-wrapper for [`sortable`](https://github.com/SortableJS/Sortable)

### @Math



[createGenericProjection](math/creategenericprojection/index)-generic version of `createProjection`


[createProjection](math/createprojection/index)-reactive numeric projection from one domain to another


[logicAnd](math/logicand/index)-`AND` condition for refs


[logicNot](math/logicnot/index)-`NOT` condition for ref


[logicOr](math/logicor/index)-`OR` conditions for refs


[useAbs](math/useabs/index)-reactive `Math.abs`


[useAverage](math/useaverage/index)-get the average of an array reactively


[useCeil](math/useceil/index)-reactive `Math.ceil`


[useClamp](math/useclamp/index)-reactively clamp a value between two other values


[useFloor](math/usefloor/index)-reactive `Math.floor`


[useMath](math/usemath/index)-reactive `Math` methods


[useMax](math/usemax/index)-reactive `Math.max`


[useMin](math/usemin/index)-reactive `Math.min`


[usePrecision](math/useprecision/index)-reactively set the precision of a number


[useProjection](math/useprojection/index)-reactive numeric projection from one domain to another


[useRound](math/useround/index)-reactive `Math.round`


[useSum](math/usesum/index)-get the sum of an array reactively


[useTrunc](math/usetrunc/index)-reactive `Math.trunc`

### @Motion



[useElementStyle](https://motion.vueuse.org/api/use-element-style.html)-sync a reactive object to a target element CSS styling


[useElementTransform](https://motion.vueuse.org/api/use-element-transform.html)-sync a reactive object to a target element CSS transform.


[useMotion](https://motion.vueuse.org/api/use-motion.html)-putting your components in motion.


[useMotionProperties](https://motion.vueuse.org/api/use-motion-properties.html)-access Motion Properties for a target element.


[useMotionVariants](https://motion.vueuse.org/api/use-motion-variants.html)-handle the Variants state and selection.


[useSpring](https://motion.vueuse.org/api/use-spring.html)-spring animations.

### @Router



[useRouteHash](router/useroutehash/index)-shorthand for a reactive `route.hash`


[useRouteParams](router/userouteparams/index)-shorthand for a reactive `route.params`


[useRouteQuery](router/useroutequery/index)-shorthand for a reactive `route.query`

### @RxJS



[from](rxjs/from/index)-/ fromEvent


[toObserver](rxjs/toobserver/index)-sugar function to convert a `ref` into an RxJS [Observer](https://rxjs.dev/guide/observer)


[useObservable](rxjs/useobservable/index)-use an RxJS [`Observable`](https://rxjs.dev/guide/observable)


[useSubject](rxjs/usesubject/index)-bind an RxJS [`Subject`](https://rxjs.dev/guide/subject) to a `ref` and propagate value changes both ways


[useSubscription](rxjs/usesubscription/index)-use an RxJS [`Subscription`](https://rxjs.dev/guide/subscription) without worrying about unsubscribing from it or creating memory leaks

### @SchemaOrg



[createSchemaOrg](https://vue-schema-org.netlify.app/api/core/create-schema-org.html)-create the schema.org manager instance.


[useSchemaOrg](https://vue-schema-org.netlify.app/api/core/use-schema-org.html)-update schema.org reactively.

### @Sound



[useSound](https://github.com/vueuse/sound#examples)-play sound effects reactively.



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/functions.html>

useScreenSafeArea
=================




|  |  |
| --- | --- |
|  Category  | [Browser](../functions#category=Browser) |
|  Export Size  | 1.49 kB |
|  Last Changed  | last year |


Reactive `env(safe-area-inset-*)`


![image](https://webkit.org/wp-content/uploads/safe-areas-1.png)


Usage
-----


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




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


Then we could use [`useScreenSafeArea`](usescreensafearea/index) in the component as shown below:




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

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


For further details, you may refer to this documentation: [Designing Websites for iPhone X](https://webkit.org/blog/7929/designing-websites-for-iphone-x/)


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../guide/components). 
> 
> 




```
<UseScreenSafeArea top right bottom left>content</UseScreenSafeArea>
```


Type Declarations
-----------------




```
/**
 * Reactive `env(safe-area-inset-*)`
 *
 * @see https://vueuse.org/useScreenSafeArea
 */
export declare function useScreenSafeArea(): {
  top: Ref<string>
  right: Ref<string>
  bottom: Ref<string>
  left: Ref<string>
  update: () => void
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useScreenSafeArea/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useScreenSafeArea/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useScreenSafeArea/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useScreenSafeArea>

onClickOutside
==============




|  |  |
| --- | --- |
|  Category  | [Sensors](../functions#category=Sensors) |
|  Export Size  | 888 B |
|  Last Changed  | 3 months ago |


Listen for clicks outside of an element. Useful for modal or dropdown.


Usage
-----




```
<template>
  <div ref="target">
    Hello world
  </div>
  <div>
    Outside element
  </div>
</template>

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

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

    onClickOutside(target, (event) => console.log(event))

    return { target }
  }
}
</script>
```



> This function uses [Event.composedPath()](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath) which is NOT supported by IE 11, Edge 18 and below. If you are targeting these browsers, we recommend you to include [this code snippet](https://gist.github.com/sibbng/13e83b1dd1b733317ce0130ef07d4efd) on your project.
> 
> 


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../guide/components). 
> 
> 




```
<OnClickOutside @trigger="count++" :options="{ ignore: [/* ... */] }">
  <div>
    Click Outside of Me
  </div>
</OnClickOutside>
```


Directive Usage
---------------



>  This function also provides a directive version via the `@vueuse/components` package. [Learn more about the usage](../guide/components). 
> 
> 




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

const modal = ref(false)
function closeModal() {
  modal.value = false
}

</script>

<template>
  <button @click="modal = true">
    Open Modal
  </button>
  <div v-if="modal" v-on-click-outside="closeModal">
    Hello World
  </div>
</template>
```


You can also set the handler as an array to set the configuration items of the instruction.




```
<script setup>
import { ref } from 'vue'
import { vOnClickOutside } from '@vueuse/components'

const modal = ref(false)

const ignoreElRef = ref()

const onClickOutsideHandler = [
  (ev) => {
    console.log(ev)
    modal.value = false
  },
  { ignore: [ignoreElRef] }
]

</script>

<template>
  <button @click="modal = true">
    Open Modal
  </button>

  <div ref="ignoreElRef">
    click outside ignore element
  </div>

  <div v-if="modal" v-on-click-outside="onClickOutsideHandler">
    Hello World
  </div>
</template>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface OnClickOutsideOptions extends ConfigurableWindow {
  /**
   * List of elements that should not trigger the event.
   */
  ignore?: (MaybeElementRef | string)[]
  /**
   * Use capturing phase for internal event listener.
   * @default true
   */
  capture?: boolean
  /**
   * Run handler function if focus moves to an iframe.
   * @default false
   */
  detectIframe?: boolean
}
export type OnClickOutsideHandler<
  T extends {
    detectIframe: OnClickOutsideOptions["detectIframe"]
  } = {
    detectIframe: false
  }
> = (
  evt: T["detectIframe"] extends true ? PointerEvent | FocusEvent : PointerEvent
) => void
/**
 * Listen for clicks outside of an element.
 *
 * @see https://vueuse.org/onClickOutside
 * @param target
 * @param handler
 * @param options
 */
export declare function onClickOutside<T extends OnClickOutsideOptions>(
  target: MaybeElementRef,
  handler: OnClickOutsideHandler<{
    detectIframe: T["detectIframe"]
  }>,
  options?: T
): (() => void) | undefined
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/onClickOutside/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/onClickOutside/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/onClickOutside/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/onClickOutside>

useStyleTag
===========




|  |  |
| --- | --- |
|  Category  | [Browser](../functions#category=Browser) |
|  Export Size  | 474 B |
|  Last Changed  | 5 months ago |


Inject reactive `style` element in head.


Usage
-----


### Basic usage


Provide a CSS string, then [`useStyleTag`](usestyletag/index) will automatically generate an id and inject it in `<head>`.




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

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

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


This code will be injected to `<head>`:




```
<style type="text/css" id="vueuse_styletag_1">
.foo { margin-top: 64px; }
</style>
```


### Custom ID


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




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

useStyleTag('.foo { margin-top: 32px; }', { id: 'custom-id' })
```




```
<!-- injected to <head> -->
<style type="text/css" id="custom-id">
.foo { margin-top: 32px; }
</style>
```


### Media query


You can pass media attributes as last argument within object.




```
useStyleTag('.foo { margin-top: 32px; }', { media: 'print' })
```




```
<!-- injected to <head> -->
<style type="text/css" id="vueuse_styletag_1" media="print">
.foo { margin-top: 32px; }
</style>
```


Type Declarations
-----------------




```
export interface UseStyleTagOptions extends ConfigurableDocument {
  /**
   * Media query for styles to apply
   */
  media?: string
  /**
   * Load the style immediately
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Manual controls the timing of loading and unloading
   *
   * @default false
   */
  manual?: boolean
  /**
   * DOM id of the style tag
   *
   * @default auto-incremented
   */
  id?: string
}
export interface UseStyleTagReturn {
  id: string
  css: Ref<string>
  load: () => void
  unload: () => void
  isLoaded: Readonly<Ref<boolean>>
}
/**
 * Inject <style> element in head.
 *
 * Overload: Omitted id
 *
 * @see https://vueuse.org/useStyleTag
 * @param css
 * @param options
 */
export declare function useStyleTag(
  css: MaybeRef<string>,
  options?: UseStyleTagOptions
): UseStyleTagReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useStyleTag/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useStyleTag/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useStyleTag/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useStyleTag>

useDocumentVisibility
=====================




|  |  |
| --- | --- |
|  Category  | [Elements](../functions#category=Elements) |
|  Export Size  | 542 B |
|  Last Changed  | 9 months ago |


Reactively track [`document.visibilityState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState)


Usage
-----




```
import { useDocumentVisibility } from '@vueuse/core'

const visibility = useDocumentVisibility()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../guide/components). 
> 
> 




```
<UseDocumentVisibility v-slot="{ visibility }">
  Document Visibility: {{ visibility }}
</UseDocumentVisibility>
```


Type Declarations
-----------------




```
/**
 * Reactively track `document.visibilityState`.
 *
 * @see https://vueuse.org/useDocumentVisibility
 * @param options
 */
export declare function useDocumentVisibility({
  document,
}?: ConfigurableDocument): Ref<DocumentVisibilityState>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDocumentVisibility/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDocumentVisibility/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDocumentVisibility/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDocumentVisibility>

useElementVisibility
====================




|  |  |
| --- | --- |
|  Category  | [Elements](../functions#category=Elements) |
|  Export Size  | 626 B |
|  Last Changed  | 2 weeks ago |


Tracks the visibility of an element within the viewport.


Usage
-----




```
<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](../guide/components). 
> 
> 




```
<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](../guide/components). 
> 
> 




```
<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>
```


Type Declarations
-----------------




```
export interface UseElementVisibilityOptions extends ConfigurableWindow {
  scrollTarget?: MaybeRefOrGetter<HTMLElement | undefined | null>
}
/**
 * Tracks the visibility of an element within the viewport.
 *
 * @see https://vueuse.org/useElementVisibility
 * @param element
 * @param options
 */
export declare function useElementVisibility(
  element: MaybeComputedElementRef,
  { window, scrollTarget }?: UseElementVisibilityOptions
): Ref<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementVisibility/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementVisibility/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementVisibility/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useElementVisibility>

useRefHistory
=============




|  |  |
| --- | --- |
|  Category  | [State](../functions#category=State) |
|  Export Size  | 1.46 kB |
|  Last Changed  | 8 months ago |
|  Related  | [`useDebouncedRefHistory`](usedebouncedrefhistory/index)[`useManualRefHistory`](usemanualrefhistory/index)[`useThrottledRefHistory`](usethrottledrefhistory/index) |


Track the change history of a ref, also provides undo and redo functionality


[Learn useRefHistory with this FREE video lesson from Vue School!](https://vueschool.io/lessons/ref-history-with-vueuse?friend=vueuse)Usage
-----




```
import { ref } from 'vue'
import { useRefHistory } from '@vueuse/core'

const counter = ref(0)
const { history, undo, redo } = useRefHistory(counter)
```


Internally, `watch` is used to trigger a history point when the ref value is modified. This means that history points are triggered asynchronously batching modifications in the same "tick".




```
counter.value += 1

await nextTick()
console.log(history.value)
/* [
  { snapshot: 1, timestamp: 1601912898062 },
  { snapshot: 0, timestamp: 1601912898061 }
] */
```


You can use `undo` to reset the ref value to the last history point.




```
console.log(counter.value) // 1
undo()
console.log(counter.value) // 0
```


### Objects / arrays


When working with objects or arrays, since changing their attributes does not change the reference, it will not trigger the committing. To track attribute changes, you would need to pass `deep: true`. It will create clones for each history record.




```
const state = ref({
  foo: 1,
  bar: 'bar',
})

const { history, undo, redo } = useRefHistory(state, {
  deep: true,
})

state.value.foo = 2

await nextTick()
console.log(history.value)
/* [
  { snapshot: { foo: 2, bar: 'bar' } },
  { snapshot: { foo: 1, bar: 'bar' } }
] */
```


#### Custom Clone Function


[`useRefHistory`](userefhistory/index) only embeds the minimal clone function `x => JSON.parse(JSON.stringify(x))`. To use a full featured or custom clone function, you can set up via the `dump` options.


For example, using [structuredClone](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone):




```
import { useRefHistory } from '@vueuse/core'

const refHistory = useRefHistory(target, { dump: structuredClone })
```


Or by using [lodash's `cloneDeep`](https://lodash.com/docs/4.17.15#cloneDeep):




```
import { cloneDeep } from 'lodash-es'
import { useRefHistory } from '@vueuse/core'

const refHistory = useRefHistory(target, { dump: cloneDeep })
```


Or a more lightweight [`klona`](https://github.com/lukeed/klona):




```
import { klona } from 'klona'
import { useRefHistory } from '@vueuse/core'

const refHistory = useRefHistory(target, { dump: klona })
```


#### Custom Dump and Parse Function


Instead of using the `clone` param, you can pass custom functions to control the serialization and parsing. In case you do not need history values to be objects, this can save an extra clone when undoing. It is also useful in case you want to have the snapshots already stringified to be saved to local storage for example.




```
import { useRefHistory } from '@vueuse/core'

const refHistory = useRefHistory(target, {
  dump: JSON.stringify,
  parse: JSON.parse,
})
```


### History Capacity


We will keep all the history by default (unlimited) until you explicitly clear them up, you can set the maximal amount of history to be kept by `capacity` options.




```
const refHistory = useRefHistory(target, {
  capacity: 15, // limit to 15 history records
})

refHistory.clear() // explicitly clear all the history
```


### History Flush Timing


From [Vue's documentation](https://vuejs.org/guide/essentials/watchers.html#callback-flush-timing): Vue's reactivity system buffers invalidated effects and flush them asynchronously to avoid unnecessary duplicate invocation when there are many state mutations happening in the same "tick".


In the same way as `watch`, you can modify the flush timing using the `flush` option.




```
const refHistory = useRefHistory(target, {
  flush: 'sync', // options 'pre' (default), 'post' and 'sync'
})
```


The default is `'pre'`, to align this composable with the default for Vue's watchers. This also helps to avoid common issues, like several history points generated as part of a multi-step update to a ref value that can break invariants of the app state. You can use `commit()` in case you need to create multiple history points in the same "tick"




```
const r = ref(0)
const { history, commit } = useRefHistory(r)

r.value = 1
commit()

r.value = 2
commit()

console.log(history.value)
/* [
  { snapshot: 2 },
  { snapshot: 1 },
  { snapshot: 0 },
] */
```


On the other hand, when using flush `'sync'`, you can use `batch(fn)` to generate a single history point for several sync operations




```
const r = ref({ names: [], version: 1 })
const { history, batch } = useRefHistory(r, { flush: 'sync' })

batch(() => {
  r.names.push('Lena')
  r.version++
})

console.log(history.value)
/* [
  { snapshot: { names: [ 'Lena' ], version: 2 },
  { snapshot: { names: [], version: 1 },
] */
```


If `{ flush: 'sync', deep: true }` is used, `batch` is also useful when doing a mutable `splice` in an array. `splice` can generate up to three atomic operations that will be pushed to the ref history.




```
const arr = ref([1, 2, 3])
const { history, batch } = useRefHistory(r, { deep: true, flush: 'sync' })

batch(() => {
  arr.value.splice(1, 1) // batch ensures only one history point is generated
})
```


Another option is to avoid mutating the original ref value using `arr.value = [...arr.value].splice(1,1)`.


Recommended Readings
--------------------


* [History and Persistence](https://patak.dev/vue/history-and-persistence.html) - by [@matias-capeletto](https://github.com/matias-capeletto)


Type Declarations
-----------------



Show Type Declarations

```
export interface UseRefHistoryOptions<Raw, Serialized = Raw>
  extends ConfigurableEventFilter {
  /**
   * Watch for deep changes, default to false
   *
   * When set to true, it will also create clones for values store in the history
   *
   * @default false
   */
  deep?: boolean
  /**
   * The flush option allows for greater control over the timing of a history point, default to 'pre'
   *
   * Possible values: 'pre', 'post', 'sync'
   * It works in the same way as the flush option in watch and watch effect in vue reactivity
   *
   * @default 'pre'
   */
  flush?: "pre" | "post" | "sync"
  /**
   * Maximum number of history to be kept. Default to unlimited.
   */
  capacity?: number
  /**
   * Clone when taking a snapshot, shortcut for dump: JSON.parse(JSON.stringify(value)).
   * Default to false
   *
   * @default false
   */
  clone?: boolean | CloneFn<Raw>
  /**
   * Serialize data into the history
   */
  dump?: (v: Raw) => Serialized
  /**
   * Deserialize data from the history
   */
  parse?: (v: Serialized) => Raw
}
export interface UseRefHistoryReturn<Raw, Serialized>
  extends UseManualRefHistoryReturn<Raw, Serialized> {
  /**
   * A ref representing if the tracking is enabled
   */
  isTracking: Ref<boolean>
  /**
   * Pause change tracking
   */
  pause(): void
  /**
   * Resume change tracking
   *
   * @param [commit] if true, a history record will be create after resuming
   */
  resume(commit?: boolean): void
  /**
   * A sugar for auto pause and auto resuming within a function scope
   *
   * @param fn
   */
  batch(fn: (cancel: Fn) => void): void
  /**
   * Clear the data and stop the watch
   */
  dispose(): void
}
/**
 * Track the change history of a ref, also provides undo and redo functionality.
 *
 * @see https://vueuse.org/useRefHistory
 * @param source
 * @param options
 */
export declare function useRefHistory<Raw, Serialized = Raw>(
  source: Ref<Raw>,
  options?: UseRefHistoryOptions<Raw, Serialized>
): UseRefHistoryReturn<Raw, Serialized>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useRefHistory/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useRefHistory/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useRefHistory/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useRefHistory>

watchIgnorable
==============




|  |  |
| --- | --- |
|  Category  | [Watch](functions#category=Watch) |
|  Export Size  | 708 B |
|  Last Changed  | 10 months ago |
|  Alias  | `ignorableWatch` |


Ignorable watch


Usage
-----


Extended `watch` that returns extra `ignoreUpdates(updater)` and `ignorePrevAsyncUpdates()` to ignore particular updates to the source.




```
import { watchIgnorable } from '@vueuse/core'
import { nextTick, ref } from 'vue'

const source = ref('foo')

const { stop, ignoreUpdates } = watchIgnorable(
  source,
  v => console.log(`Changed to ${v}!`),
)

source.value = 'bar'
await nextTick() // logs: Changed to bar!

ignoreUpdates(() => {
  source.value = 'foobar'
})
await nextTick() // (nothing happened)

source.value = 'hello'
await nextTick() // logs: Changed to hello!

ignoreUpdates(() => {
  source.value = 'ignored'
})
source.value = 'logged'

await nextTick() // logs: Changed to logged!
```


Flush timing
------------


[`watchIgnorable`](shared/watchignorable/index) accepts the same options as `watch` and uses the same defaults. So, by default the composable works using `flush: 'pre'`.



`ignorePrevAsyncUpdates`
-------------------------


This feature is only for async flush `'pre'` and `'post'`. If `flush: 'sync'` is used, `ignorePrevAsyncUpdates()` is a no-op as the watch will trigger immediately after each update to the source. It is still provided for sync flush so the code can be more generic.




```
import { watchIgnorable } from '@vueuse/core'
import { nextTick, ref } from 'vue'

const source = ref('foo')

const { ignorePrevAsyncUpdates } = watchIgnorable(
  source,
  v => console.log(`Changed to ${v}!`),
)

source.value = 'bar'
await nextTick() // logs: Changed to bar!

source.value = 'good'
source.value = 'by'
ignorePrevAsyncUpdates()

await nextTick() // (nothing happened)

source.value = 'prev'
ignorePrevAsyncUpdates()
source.value = 'after'

await nextTick() // logs: Changed to after!
```


Recommended Readings
--------------------


* [Ignorable Watch](https://patak.dev/vue/ignorable-watch.html) - by [@matias-capeletto](https://github.com/matias-capeletto)


Type Declarations
-----------------



Show Type Declarations

```
export type IgnoredUpdater = (updater: () => void) => void
export interface WatchIgnorableReturn {
  ignoreUpdates: IgnoredUpdater
  ignorePrevAsyncUpdates: () => void
  stop: WatchStopHandle
}
export declare function watchIgnorable<
  T extends Readonly<WatchSource<unknown>[]>,
  Immediate extends Readonly<boolean> = false
>(
  sources: [...T],
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options?: WatchWithFilterOptions<Immediate>
): WatchIgnorableReturn
export declare function watchIgnorable<
  T,
  Immediate extends Readonly<boolean> = false
>(
  source: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>
): WatchIgnorableReturn
export declare function watchIgnorable<
  T extends object,
  Immediate extends Readonly<boolean> = false
>(
  source: T,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>
): WatchIgnorableReturn
export { watchIgnorable as ignorableWatch }
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchIgnorable/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchIgnorable/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchIgnorable/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/ignorableWatch>

useAsyncQueue
=============




|  |  |
| --- | --- |
|  Category  | [Utilities](../functions#category=Utilities) |
|  Export Size  | 391 B |
|  Last Changed  | last year |


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


Usage
-----




```
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
```


Type Declarations
-----------------



Show Type Declarations

```
export type UseAsyncQueueTask<T> = (...args: any[]) => T | Promise<T>
export interface UseAsyncQueueResult<T> {
  state: "pending" | "fulfilled" | "rejected"
  data: T | null
}
export interface UseAsyncQueueReturn<T> {
  activeIndex: Ref<number>
  result: T
}
export interface UseAsyncQueueOptions {
  /**
   * Interrupt tasks when current task fails.
   *
   * @default true
   */
  interrupt?: boolean
  /**
   * Trigger it when the tasks fails.
   *
   */
  onError?: () => void
  /**
   * Trigger it when the tasks ends.
   *
   */
  onFinished?: () => void
}
/**
 * Asynchronous queue task controller.
 *
 * @see https://vueuse.org/useAsyncQueue
 * @param tasks
 * @param options
 */
export declare function useAsyncQueue<T1>(
  tasks: [UseAsyncQueueTask<T1>],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<[UseAsyncQueueResult<T1>]>
export declare function useAsyncQueue<T1, T2>(
  tasks: [UseAsyncQueueTask<T1>, UseAsyncQueueTask<T2>],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<[UseAsyncQueueResult<T1>, UseAsyncQueueResult<T2>]>
export declare function useAsyncQueue<T1, T2, T3>(
  tasks: [UseAsyncQueueTask<T1>, UseAsyncQueueTask<T2>, UseAsyncQueueTask<T3>],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<
  [UseAsyncQueueResult<T1>, UseAsyncQueueResult<T2>, UseAsyncQueueResult<T3>]
>
export declare function useAsyncQueue<T1, T2, T3, T4>(
  tasks: [
    UseAsyncQueueTask<T1>,
    UseAsyncQueueTask<T2>,
    UseAsyncQueueTask<T3>,
    UseAsyncQueueTask<T4>
  ],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<
  [
    UseAsyncQueueResult<T1>,
    UseAsyncQueueResult<T2>,
    UseAsyncQueueResult<T3>,
    UseAsyncQueueResult<T4>
  ]
>
export declare function useAsyncQueue<T1, T2, T3, T4, T5>(
  tasks: [
    UseAsyncQueueTask<T1>,
    UseAsyncQueueTask<T2>,
    UseAsyncQueueTask<T3>,
    UseAsyncQueueTask<T4>,
    UseAsyncQueueTask<T5>
  ],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<
  [
    UseAsyncQueueResult<T1>,
    UseAsyncQueueResult<T2>,
    UseAsyncQueueResult<T3>,
    UseAsyncQueueResult<T4>,
    UseAsyncQueueResult<T5>
  ]
>
export declare function useAsyncQueue<T>(
  tasks: UseAsyncQueueTask<T>[],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<UseAsyncQueueResult<T>[]>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useAsyncQueue/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useAsyncQueue/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useAsyncQueue/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useAsyncQueue>

useTransition
=============




|  |  |
| --- | --- |
|  Category  | [Animation](../functions#category=Animation) |
|  Export Size  | 1.14 kB |
|  Last Changed  | last week |


Transition between values


Usage
-----


Define a numeric source value to follow, and when changed the output will transition to the new value. If the source changes while a transition is in progress, a new transition will begin from where the previous one was interrupted.




```
import { ref } from 'vue'
import { TransitionPresets, useTransition } from '@vueuse/core'

const source = ref(0)

const output = useTransition(source, {
  duration: 1000,
  transition: TransitionPresets.easeInOutCubic,
})
```


To synchronize transitions, use an array of numbers. As an example, here is how we could transition between colors.




```
const source = ref([0, 0, 0])

const output = useTransition(source)

const color = computed(() => {
  const [r, g, b] = output.value
  return `rgb(${r}, ${g}, ${b})`
})
```


Transition easing can be customized using cubic bezier curves. Transitions defined this way work the same as [CSS easing functions](https://developer.mozilla.org/en-US/docs/Web/CSS/easing-function#easing_functions).




```
useTransition(source, {
  transition: [0.75, 0, 0.25, 1],
})
```


The following transitions are available via the `TransitionPresets` constant.


* [`linear`](https://cubic-bezier.com/#0,0,1,1)
* [`easeInSine`](https://cubic-bezier.com/#.12,0,.39,0)
* [`easeOutSine`](https://cubic-bezier.com/#.61,1,.88,1)
* [`easeInOutSine`](https://cubic-bezier.com/#.37,0,.63,1)
* [`easeInQuad`](https://cubic-bezier.com/#.11,0,.5,0)
* [`easeOutQuad`](https://cubic-bezier.com/#.5,1,.89,1)
* [`easeInOutQuad`](https://cubic-bezier.com/#.45,0,.55,1)
* [`easeInCubic`](https://cubic-bezier.com/#.32,0,.67,0)
* [`easeOutCubic`](https://cubic-bezier.com/#.33,1,.68,1)
* [`easeInOutCubic`](https://cubic-bezier.com/#.65,0,.35,1)
* [`easeInQuart`](https://cubic-bezier.com/#.5,0,.75,0)
* [`easeOutQuart`](https://cubic-bezier.com/#.25,1,.5,1)
* [`easeInOutQuart`](https://cubic-bezier.com/#.76,0,.24,1)
* [`easeInQuint`](https://cubic-bezier.com/#.64,0,.78,0)
* [`easeOutQuint`](https://cubic-bezier.com/#.22,1,.36,1)
* [`easeInOutQuint`](https://cubic-bezier.com/#.83,0,.17,1)
* [`easeInExpo`](https://cubic-bezier.com/#.7,0,.84,0)
* [`easeOutExpo`](https://cubic-bezier.com/#.16,1,.3,1)
* [`easeInOutExpo`](https://cubic-bezier.com/#.87,0,.13,1)
* [`easeInCirc`](https://cubic-bezier.com/#.55,0,1,.45)
* [`easeOutCirc`](https://cubic-bezier.com/#0,.55,.45,1)
* [`easeInOutCirc`](https://cubic-bezier.com/#.85,0,.15,1)
* [`easeInBack`](https://cubic-bezier.com/#.36,0,.66,-.56)
* [`easeOutBack`](https://cubic-bezier.com/#.34,1.56,.64,1)
* [`easeInOutBack`](https://cubic-bezier.com/#.68,-.6,.32,1.6)


For more complex transitions, a custom function can be provided.




```
function easeOutElastic(n) {
  return n === 0
    ? 0
    : n === 1
      ? 1
      : (2 ** (-10 * n)) * Math.sin((n * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1
}

useTransition(source, {
  transition: easeOutElastic,
})
```


To control when a transition starts, set a `delay` value. To choreograph behavior around a transition, define `onStarted` or `onFinished` callbacks.




```
useTransition(source, {
  delay: 1000,
  onStarted() {
    // called after the transition starts
  },
  onFinished() {
    // called after the transition ends
  },
})
```


To temporarily stop transitioning, define a boolean `disabled` property. Be aware, this is not the same a `duration` of `0`. Disabled transitions track the source value ***synchronously***. They do not respect a `delay`, and do not fire `onStarted` or `onFinished` callbacks.


For more control, transitions can be executed manually by using `executeTransition`. This function returns a promise that resolves upon completion. Manual transitions can be cancelled by defining an `abort` function that returns a truthy value.




```
import { executeTransition } from '@vueuse/core'

await executeTransition(source, from, to, {
  duration: 1000,
})
```


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Cubic bezier points
 */
export type CubicBezierPoints = [number, number, number, number]
/**
 * Easing function
 */
export type EasingFunction = (n: number) => number
/**
 * Transition options
 */
export interface TransitionOptions {
  /**
   * Manually abort a transition
   */
  abort?: () => any
  /**
   * Transition duration in milliseconds
   */
  duration?: MaybeRef<number>
  /**
   * Easing function or cubic bezier points for calculating transition values
   */
  transition?: MaybeRef<EasingFunction | CubicBezierPoints>
}
export interface UseTransitionOptions extends TransitionOptions {
  /**
   * Milliseconds to wait before starting transition
   */
  delay?: MaybeRef<number>
  /**
   * Disables the transition
   */
  disabled?: MaybeRef<boolean>
  /**
   * Callback to execute after transition finishes
   */
  onFinished?: () => void
  /**
   * Callback to execute after transition starts
   */
  onStarted?: () => void
}
/**
 * Common transitions
 *
 * @see https://easings.net
 */
export declare const TransitionPresets: Record<
  | "easeInSine"
  | "easeOutSine"
  | "easeInOutSine"
  | "easeInQuad"
  | "easeOutQuad"
  | "easeInOutQuad"
  | "easeInCubic"
  | "easeOutCubic"
  | "easeInOutCubic"
  | "easeInQuart"
  | "easeOutQuart"
  | "easeInOutQuart"
  | "easeInQuint"
  | "easeOutQuint"
  | "easeInOutQuint"
  | "easeInExpo"
  | "easeOutExpo"
  | "easeInOutExpo"
  | "easeInCirc"
  | "easeOutCirc"
  | "easeInOutCirc"
  | "easeInBack"
  | "easeOutBack"
  | "easeInOutBack",
  CubicBezierPoints
> & {
  linear: EasingFunction
}
/**
 * Transition from one value to another.
 *
 * @param source
 * @param from
 * @param to
 * @param options
 */
export declare function executeTransition<T extends number | number[]>(
  source: Ref<T>,
  from: MaybeRefOrGetter<T>,
  to: MaybeRefOrGetter<T>,
  options?: TransitionOptions
): PromiseLike<void>
export declare function useTransition(
  source: MaybeRefOrGetter<number>,
  options?: UseTransitionOptions
): ComputedRef<number>
export declare function useTransition<T extends MaybeRefOrGetter<number>[]>(
  source: [...T],
  options?: UseTransitionOptions
): ComputedRef<{
  [K in keyof T]: number
}>
export declare function useTransition<T extends MaybeRefOrGetter<number[]>>(
  source: T,
  options?: UseTransitionOptions
): ComputedRef<number[]>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTransition/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTransition/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTransition/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTransition>

useSwipe
========




|  |  |
| --- | --- |
|  Category  | [Sensors](../functions#category=Sensors) |
|  Export Size  | 983 B |
|  Last Changed  | 2 days ago |


Reactive swipe detection based on [`TouchEvents`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent).


Usage
-----




```
<template>
  <div ref="el">
    Swipe here
  </div>
</template>

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

    return { el, isSwiping, direction }
  } 
</script>
```


Type Declarations
-----------------



Show Type Declarations

```
export type UseSwipeDirection = "up" | "down" | "left" | "right" | "none"
export interface UseSwipeOptions extends ConfigurableWindow {
  /**
   * Register events as passive
   *
   * @default true
   */
  passive?: boolean
  /**
   * @default 50
   */
  threshold?: number
  /**
   * Callback on swipe start
   */
  onSwipeStart?: (e: TouchEvent) => void
  /**
   * Callback on swipe moves
   */
  onSwipe?: (e: TouchEvent) => void
  /**
   * Callback on swipe ends
   */
  onSwipeEnd?: (e: TouchEvent, direction: UseSwipeDirection) => void
}
export interface UseSwipeReturn {
  isPassiveEventSupported: boolean
  isSwiping: Ref<boolean>
  direction: ComputedRef<UseSwipeDirection>
  coordsStart: Readonly<Position>
  coordsEnd: Readonly<Position>
  lengthX: ComputedRef<number>
  lengthY: ComputedRef<number>
  stop: () => void
}
/**
 * Reactive swipe detection.
 *
 * @see https://vueuse.org/useSwipe
 * @param target
 * @param options
 */
export declare function useSwipe(
  target: MaybeRefOrGetter<EventTarget | null | undefined>,
  options?: UseSwipeOptions
): UseSwipeReturn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useSwipe/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useSwipe/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useSwipe/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useSwipe>

useUrlSearchParams
==================




|  |  |
| --- | --- |
|  Category  | [Browser](../functions#category=Browser) |
|  Export Size  | 1.59 kB |
|  Last Changed  | 8 months ago |


Reactive [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)


Usage
-----




```
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`




```
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`




```
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`
```


Type Declarations
-----------------




```
export type UrlParams = Record<string, string[] | string>
export interface UseUrlSearchParamsOptions<T> extends ConfigurableWindow {
  /**
   * @default true
   */
  removeNullishValues?: boolean
  /**
   * @default false
   */
  removeFalsyValues?: boolean
  /**
   * @default {}
   */
  initialValue?: T
  /**
   * Write back to `window.history` automatically
   *
   * @default true
   */
  write?: boolean
}
/**
 * Reactive URLSearchParams
 *
 * @see https://vueuse.org/useUrlSearchParams
 * @param mode
 * @param options
 */
export declare function useUrlSearchParams<
  T extends Record<string, any> = UrlParams
>(
  mode?: "history" | "hash" | "hash-params",
  options?: UseUrlSearchParamsOptions<T>
): T
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useUrlSearchParams/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useUrlSearchParams/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useUrlSearchParams/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useUrlSearchParams>

useElementByPoint
=================




|  |  |
| --- | --- |
|  Category  | [Sensors](../functions#category=Sensors) |
|  Export Size  | 642 B |
|  Last Changed  | 2 weeks ago |


Reactive element by point.


Usage
-----




```
import { useElementByPoint, useMouse } from '@vueuse/core'

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


Type Declarations
-----------------




```
export interface UseElementByPointOptions extends ConfigurableDocument {
  x: MaybeRefOrGetter<number>
  y: MaybeRefOrGetter<number>
}
/**
 * Reactive element by point.
 *
 * @see https://vueuse.org/useElementByPoint
 * @param options - UseElementByPointOptions
 */
export declare function useElementByPoint(options: UseElementByPointOptions): {
  isActive: Readonly<Ref<boolean>>
  pause: Fn
  resume: Fn
  element: Ref<HTMLElement | null>
}
export type UseElementByPointReturn = ReturnType<typeof useElementByPoint>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementByPoint/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementByPoint/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementByPoint/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useElementByPoint>

useFetch
========




|  |  |
| --- | --- |
|  Category  | [Network](../functions#category=Network) |
|  Export Size  | 2.42 kB |
|  Last Changed  | 2 weeks ago |


Reactive [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provides the ability to abort requests, intercept requests before they are fired, automatically refetch requests when the url changes, and create your own [`useFetch`](usefetch/index) with predefined options.


[Learn useFetch with this FREE video lesson from Vue School!](https://vueschool.io/lessons/vueuse-utilities-usefetch-and-reactify?friend=vueuse)
**TIP**When using with Nuxt 3, this functions will **NOT** be auto imported in favor of Nuxt's built-in [`useFetch()`](https://v3.nuxtjs.org/api/composables/use-fetch). Use explicit import if you want to use the function from VueUse.



Usage
-----


### Basic Usage


The [`useFetch`](usefetch/index) function can be used by simply providing a url. The url can be either a string or a `ref`. The `data` object will contain the result of the request, the `error` object will contain any errors, and the `isFetching` object will indicate if the request is loading.




```
import { useFetch } from '@vueuse/core'

const { isFetching, error, data } = useFetch(url)
```


### Asynchronous Usage


[`useFetch`](usefetch/index) can also be awaited just like a normal fetch. Note that whenever a component is asynchronous, whatever component that uses it must wrap the component in a `<Suspense>` tag. You can read more about the suspense api in the [Offical Vue 3 Docs](https://vuejs.org/guide/built-ins/suspense.html)




```
import { useFetch } from '@vueuse/core'

const { isFetching, error, data } = await useFetch(url)
```


### Refetching on URL change


Using a `ref` for the url parameter will allow the [`useFetch`](usefetch/index) function to automatically trigger another request when the url is changed.




```
const url = ref('https://my-api.com/user/1')

const { data } = useFetch(url, { refetch: true })

url.value = 'https://my-api.com/user/2' // Will trigger another request
```


### Prevent request from firing immediately


Setting the `immediate` option to false will prevent the request from firing until the `execute` function is called.




```
const { execute } = useFetch(url, { immediate: false })

execute()
```


### Aborting a request


A request can be aborted by using the `abort` function from the [`useFetch`](usefetch/index) function. The `canAbort` property indicates if the request can be aborted.




```
const { abort, canAbort } = useFetch(url)

setTimeout(() => {
  if (canAbort.value)
    abort()
}, 100)
```


A request can also be aborted automatically by using `timeout` property. It will call `abort` function when the given timeout is reached.




```
const { data } = useFetch(url, { timeout: 100 })
```


### Intercepting a request


The `beforeFetch` option can intercept a request before it is sent and modify the request options and url.




```
const { data } = useFetch(url, {
  async beforeFetch({ url, options, cancel }) {
    const myToken = await getMyToken()

    if (!myToken)
      cancel()

    options.headers = {
      ...options.headers,
      Authorization: `Bearer ${myToken}`,
    }

    return {
      options,
    }
  },
})
```


The `afterFetch` option can intercept the response data before it is updated.




```
const { data } = useFetch(url, {
  afterFetch(ctx) {
    if (ctx.data.title === 'HxH')
      ctx.data.title = 'Hunter x Hunter' // Modifies the response data

    return ctx
  },
})
```


The `onFetchError` option can intercept the response data and error before it is updated.




```
const { data } = useFetch(url, {
  onFetchError(ctx) {
    // ctx.data can be null when 5xx response
    if (ctx.data === null)
      ctx.data = { title: 'Hunter x Hunter' } // Modifies the response data

    ctx.error = new Error('Custom Error') // Modifies the error

    return ctx
  },
})
```


### Setting the request method and return type


The request method and return type can be set by adding the appropriate methods to the end of `useFetch`




```
// Request will be sent with GET method and data will be parsed as JSON
const { data } = useFetch(url).get().json()

// Request will be sent with POST method and data will be parsed as text
const { data } = useFetch(url).post().text()

// Or set the method using the options

// Request will be sent with GET method and data will be parsed as blob
const { data } = useFetch(url, { method: 'GET' }, { refetch: true }).blob()
```


### Creating a Custom Instance


The `createFetch` function will return a useFetch function with whatever pre-configured options that are provided to it. This is useful for interacting with API's throughout an application that uses the same base URL or needs Authorization headers.




```
const useMyFetch = createFetch({
  baseUrl: 'https://my-api.com',
  options: {
    async beforeFetch({ options }) {
      const myToken = await getMyToken()
      options.headers.Authorization = `Bearer ${myToken}`

      return { options }
    },
  },
  fetchOptions: {
    mode: 'cors',
  },
})

const { isFetching, error, data } = useMyFetch('users')
```


If you want to control the behavior of `beforeFetch`, `afterFetch`, `onFetchError` between the pre-configured instance and newly spawned instance. You can provide a `combination` option to toggle between `overwrite` or `chaining`.




```
const useMyFetch = createFetch({
  baseUrl: 'https://my-api.com',
  combination: 'overwrite',
  options: {
    // beforeFetch in pre-configured instance will only run when the newly spawned instance do not pass beforeFetch
    async beforeFetch({ options }) {
      const myToken = await getMyToken()
      options.headers.Authorization = `Bearer ${myToken}`

      return { options }
    },
  },
})

// use useMyFetch beforeFetch
const { isFetching, error, data } = useMyFetch('users')

// use custom beforeFetch
const { isFetching, error, data } = useMyFetch('users', {
  async beforeFetch({ url, options, cancel }) {
    const myToken = await getMyToken()

    if (!myToken)
      cancel()

    options.headers = {
      ...options.headers,
      Authorization: `Bearer ${myToken}`,
    }

    return {
      options,
    }
  },
})
```


### Events


The `onFetchResponse` and `onFetchError` will fire on fetch request responses and errors respectively.




```
const { onFetchResponse, onFetchError } = useFetch(url)

onFetchResponse((response) => {
  console.log(response.status)
})

onFetchError((error) => {
  console.error(error.message)
})
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseFetchReturn<T> {
  /**
   * Indicates if the fetch request has finished
   */
  isFinished: Ref<boolean>
  /**
   * The statusCode of the HTTP fetch response
   */
  statusCode: Ref<number | null>
  /**
   * The raw response of the fetch response
   */
  response: Ref<Response | null>
  /**
   * Any fetch errors that may have occurred
   */
  error: Ref<any>
  /**
   * The fetch response body on success, may either be JSON or text
   */
  data: Ref<T | null>
  /**
   * Indicates if the request is currently being fetched.
   */
  isFetching: Ref<boolean>
  /**
   * Indicates if the fetch request is able to be aborted
   */
  canAbort: ComputedRef<boolean>
  /**
   * Indicates if the fetch request was aborted
   */
  aborted: Ref<boolean>
  /**
   * Abort the fetch request
   */
  abort: Fn
  /**
   * Manually call the fetch
   * (default not throwing error)
   */
  execute: (throwOnFailed?: boolean) => Promise<any>
  /**
   * Fires after the fetch request has finished
   */
  onFetchResponse: EventHookOn<Response>
  /**
   * Fires after a fetch request error
   */
  onFetchError: EventHookOn
  /**
   * Fires after a fetch has completed
   */
  onFetchFinally: EventHookOn
  get(): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  post(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  put(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  delete(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  patch(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  head(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  options(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  json<JSON = any>(): UseFetchReturn<JSON> & PromiseLike<UseFetchReturn<JSON>>
  text(): UseFetchReturn<string> & PromiseLike<UseFetchReturn<string>>
  blob(): UseFetchReturn<Blob> & PromiseLike<UseFetchReturn<Blob>>
  arrayBuffer(): UseFetchReturn<ArrayBuffer> &
    PromiseLike<UseFetchReturn<ArrayBuffer>>
  formData(): UseFetchReturn<FormData> & PromiseLike<UseFetchReturn<FormData>>
}
type Combination = "overwrite" | "chain"
export interface BeforeFetchContext {
  /**
   * The computed url of the current request
   */
  url: string
  /**
   * The request options of the current request
   */
  options: RequestInit
  /**
   * Cancels the current request
   */
  cancel: Fn
}
export interface AfterFetchContext<T = any> {
  response: Response
  data: T | null
}
export interface OnFetchErrorContext<T = any, E = any> {
  error: E
  data: T | null
}
export interface UseFetchOptions {
  /**
   * Fetch function
   */
  fetch?: typeof window.fetch
  /**
   * Will automatically run fetch when `useFetch` is used
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Will automatically refetch when:
   * - the URL is changed if the URL is a ref
   * - the payload is changed if the payload is a ref
   *
   * @default false
   */
  refetch?: MaybeRefOrGetter<boolean>
  /**
   * Initial data before the request finished
   *
   * @default null
   */
  initialData?: any
  /**
   * Timeout for abort request after number of millisecond
   * `0` means use browser default
   *
   * @default 0
   */
  timeout?: number
  /**
   * Will run immediately before the fetch request is dispatched
   */
  beforeFetch?: (
    ctx: BeforeFetchContext
  ) =>
    | Promise<Partial<BeforeFetchContext> | void>
    | Partial<BeforeFetchContext>
    | void
  /**
   * Will run immediately after the fetch request is returned.
   * Runs after any 2xx response
   */
  afterFetch?: (
    ctx: AfterFetchContext
  ) => Promise<Partial<AfterFetchContext>> | Partial<AfterFetchContext>
  /**
   * Will run immediately after the fetch request is returned.
   * Runs after any 4xx and 5xx response
   */
  onFetchError?: (ctx: {
    data: any
    response: Response | null
    error: any
  }) => Promise<Partial<OnFetchErrorContext>> | Partial<OnFetchErrorContext>
}
export interface CreateFetchOptions {
  /**
   * The base URL that will be prefixed to all urls unless urls are absolute
   */
  baseUrl?: MaybeRefOrGetter<string>
  /**
   * Determine the inherit behavior for beforeFetch, afterFetch, onFetchError
   * @default 'chain'
   */
  combination?: Combination
  /**
   * Default Options for the useFetch function
   */
  options?: UseFetchOptions
  /**
   * Options for the fetch request
   */
  fetchOptions?: RequestInit
}
export declare function createFetch(
  config?: CreateFetchOptions
): typeof useFetch
export declare function useFetch<T>(
  url: MaybeRefOrGetter<string>
): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
export declare function useFetch<T>(
  url: MaybeRefOrGetter<string>,
  useFetchOptions: UseFetchOptions
): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
export declare function useFetch<T>(
  url: MaybeRefOrGetter<string>,
  options: RequestInit,
  useFetchOptions?: UseFetchOptions
): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useFetch/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useFetch/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useFetch/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useFetch>

useMediaControls
================




|  |  |
| --- | --- |
|  Category  | [Browser](../functions#category=Browser) |
|  Export Size  | 2.36 kB |
|  Last Changed  | 4 days ago |


Reactive media controls for both `audio` and `video` elements


Usage
-----


### Basic Usage




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

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

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

<template>
  <video ref="video" />
  <button @click="playing = !playing">Play / Pause</button>
  <span>{{ currentTime }} / {{ duration }}</span>
</template>
```


### Providing Captions, Subtitles, etc...


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




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

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


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Many of the jsdoc definitions here are modified version of the
 * documentation from MDN(https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement)
 */
export interface UseMediaSource {
  /**
   * The source url for the media
   */
  src: string
  /**
   * The media codec type
   */
  type?: string
}
export interface UseMediaTextTrackSource {
  /**
   * Indicates that the track should be enabled unless the user's preferences indicate
   * that another track is more appropriate
   */
  default?: boolean
  /**
   * How the text track is meant to be used. If omitted the default kind is subtitles.
   */
  kind: TextTrackKind
  /**
   * A user-readable title of the text track which is used by the browser
   * when listing available text tracks.
   */
  label: string
  /**
   * Address of the track (.vtt file). Must be a valid URL. This attribute
   * must be specified and its URL value must have the same origin as the document
   */
  src: string
  /**
   * Language of the track text data. It must be a valid BCP 47 language tag.
   * If the kind attribute is set to subtitles, then srclang must be defined.
   */
  srcLang: string
}
interface UseMediaControlsOptions extends ConfigurableDocument {
  /**
   * The source for the media, may either be a string, a `UseMediaSource` object, or a list
   * of `UseMediaSource` objects.
   */
  src?: MaybeRefOrGetter<string | UseMediaSource | UseMediaSource[]>
  /**
   * A list of text tracks for the media
   */
  tracks?: MaybeRefOrGetter<UseMediaTextTrackSource[]>
}
export interface UseMediaTextTrack {
  /**
   * The index of the text track
   */
  id: number
  /**
   * The text track label
   */
  label: string
  /**
   * Language of the track text data. It must be a valid BCP 47 language tag.
   * If the kind attribute is set to subtitles, then srclang must be defined.
   */
  language: string
  /**
   * Specifies the display mode of the text track, either `disabled`,
   * `hidden`, or `showing`
   */
  mode: TextTrackMode
  /**
   * How the text track is meant to be used. If omitted the default kind is subtitles.
   */
  kind: TextTrackKind
  /**
   * Indicates the track's in-band metadata track dispatch type.
   */
  inBandMetadataTrackDispatchType: string
  /**
   * A list of text track cues
   */
  cues: TextTrackCueList | null
  /**
   * A list of active text track cues
   */
  activeCues: TextTrackCueList | null
}
export declare function useMediaControls(
  target: MaybeRef<HTMLMediaElement | null | undefined>,
  options?: UseMediaControlsOptions
): {
  currentTime: Ref<number>
  duration: Ref<number>
  waiting: Ref<boolean>
  seeking: Ref<boolean>
  ended: Ref<boolean>
  stalled: Ref<boolean>
  buffered: Ref<[number, number][]>
  playing: Ref<boolean>
  rate: Ref<number>
  volume: Ref<number>
  muted: Ref<boolean>
  tracks: Ref<
    {
      id: number
      label: string
      language: string
      mode: TextTrackMode
      kind: TextTrackKind
      inBandMetadataTrackDispatchType: string
      cues: {
        [x: number]: {
          endTime: number
          id: string
          onenter: ((this: TextTrackCue, ev: Event) => any) | null
          onexit: ((this: TextTrackCue, ev: Event) => any) | null
          pauseOnExit: boolean
          startTime: number
          readonly track: {
            readonly activeCues: any | null
            readonly cues: any | null
            readonly id: string
            readonly inBandMetadataTrackDispatchType: string
            readonly kind: TextTrackKind
            readonly label: string
            readonly language: string
            mode: TextTrackMode
            oncuechange: ((this: TextTrack, ev: Event) => any) | null
            addCue: (cue: TextTrackCue) => void
            removeCue: (cue: TextTrackCue) => void
            addEventListener: {
              <K extends "cuechange">(
                type: K,
                listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any,
                options?: boolean | AddEventListenerOptions | undefined
              ): void
              (
                type: string,
                listener: EventListenerOrEventListenerObject,
                options?: boolean | AddEventListenerOptions | undefined
              ): void
            }
            removeEventListener: {
              <K_1 extends "cuechange">(
                type: K_1,
                listener: (this: TextTrack, ev: TextTrackEventMap[K_1]) => any,
                options?: boolean | EventListenerOptions | undefined
              ): void
              (
                type: string,
                listener: EventListenerOrEventListenerObject,
                options?: boolean | EventListenerOptions | undefined
              ): void
            }
            dispatchEvent: (event: Event) => boolean
          } | null
          addEventListener: {
            <K_2 extends keyof TextTrackCueEventMap>(
              type: K_2,
              listener: (
                this: TextTrackCue,
                ev: TextTrackCueEventMap[K_2]
              ) => any,
              options?: boolean | AddEventListenerOptions | undefined
            ): void
            (
              type: string,
              listener: EventListenerOrEventListenerObject,
              options?: boolean | AddEventListenerOptions | undefined
            ): void
          }
          removeEventListener: {
            <K_3 extends keyof TextTrackCueEventMap>(
              type: K_3,
              listener: (
                this: TextTrackCue,
                ev: TextTrackCueEventMap[K_3]
              ) => any,
              options?: boolean | EventListenerOptions | undefined
            ): void
            (
              type: string,
              listener: EventListenerOrEventListenerObject,
              options?: boolean | EventListenerOptions | undefined
            ): void
          }
          dispatchEvent: (event: Event) => boolean
        }
        readonly length: number
        getCueById: (id: string) => TextTrackCue | null
        [Symbol.iterator]: () => IterableIterator<TextTrackCue>
      } | null
      activeCues: {
        [x: number]: {
          endTime: number
          id: string
          onenter: ((this: TextTrackCue, ev: Event) => any) | null
          onexit: ((this: TextTrackCue, ev: Event) => any) | null
          pauseOnExit: boolean
          startTime: number
          readonly track: {
            readonly activeCues: any | null
            readonly cues: any | null
            readonly id: string
            readonly inBandMetadataTrackDispatchType: string
            readonly kind: TextTrackKind
            readonly label: string
            readonly language: string
            mode: TextTrackMode
            oncuechange: ((this: TextTrack, ev: Event) => any) | null
            addCue: (cue: TextTrackCue) => void
            removeCue: (cue: TextTrackCue) => void
            addEventListener: {
              <K extends "cuechange">(
                type: K,
                listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any,
                options?: boolean | AddEventListenerOptions | undefined
              ): void
              (
                type: string,
                listener: EventListenerOrEventListenerObject,
                options?: boolean | AddEventListenerOptions | undefined
              ): void
            }
            removeEventListener: {
              <K_1 extends "cuechange">(
                type: K_1,
                listener: (this: TextTrack, ev: TextTrackEventMap[K_1]) => any,
                options?: boolean | EventListenerOptions | undefined
              ): void
              (
                type: string,
                listener: EventListenerOrEventListenerObject,
                options?: boolean | EventListenerOptions | undefined
              ): void
            }
            dispatchEvent: (event: Event) => boolean
          } | null
          addEventListener: {
            <K_2 extends keyof TextTrackCueEventMap>(
              type: K_2,
              listener: (
                this: TextTrackCue,
                ev: TextTrackCueEventMap[K_2]
              ) => any,
              options?: boolean | AddEventListenerOptions | undefined
            ): void
            (
              type: string,
              listener: EventListenerOrEventListenerObject,
              options?: boolean | AddEventListenerOptions | undefined
            ): void
          }
          removeEventListener: {
            <K_3 extends keyof TextTrackCueEventMap>(
              type: K_3,
              listener: (
                this: TextTrackCue,
                ev: TextTrackCueEventMap[K_3]
              ) => any,
              options?: boolean | EventListenerOptions | undefined
            ): void
            (
              type: string,
              listener: EventListenerOrEventListenerObject,
              options?: boolean | EventListenerOptions | undefined
            ): void
          }
          dispatchEvent: (event: Event) => boolean
        }
        readonly length: number
        getCueById: (id: string) => TextTrackCue | null
        [Symbol.iterator]: () => IterableIterator<TextTrackCue>
      } | null
    }[]
  >
  selectedTrack: Ref<number>
  enableTrack: (
    track: number | UseMediaTextTrack,
    disableTracks?: boolean
  ) => void
  disableTrack: (track?: number | UseMediaTextTrack) => void
  supportsPictureInPicture: boolean | undefined
  togglePictureInPicture: () => Promise<unknown>
  isPictureInPicture: Ref<boolean>
  onSourceError: EventHookOn<Event>
}
export type UseMediaControlsReturn = ReturnType<typeof useMediaControls>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMediaControls/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMediaControls/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMediaControls/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMediaControls>

onClickOutside
==============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 888 B |
|  Last Changed  | 3 months ago |


Listen for clicks outside of an element. Useful for modal or dropdown.


Usage
-----




```
<template>
  <div ref="target">
    Hello world
  </div>
  <div>
    Outside element
  </div>
</template>

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

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

    onClickOutside(target, (event) => console.log(event))

    return { target }
  }
}
</script>
```



> This function uses [Event.composedPath()](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath) which is NOT supported by IE 11, Edge 18 and below. If you are targeting these browsers, we recommend you to include [this code snippet](https://gist.github.com/sibbng/13e83b1dd1b733317ce0130ef07d4efd) on your project.
> 
> 


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<OnClickOutside @trigger="count++" :options="{ ignore: [/* ... */] }">
  <div>
    Click Outside of Me
  </div>
</OnClickOutside>
```


Directive Usage
---------------



>  This function also provides a directive version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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

const modal = ref(false)
function closeModal() {
  modal.value = false
}

</script>

<template>
  <button @click="modal = true">
    Open Modal
  </button>
  <div v-if="modal" v-on-click-outside="closeModal">
    Hello World
  </div>
</template>
```


You can also set the handler as an array to set the configuration items of the instruction.




```
<script setup>
import { ref } from 'vue'
import { vOnClickOutside } from '@vueuse/components'

const modal = ref(false)

const ignoreElRef = ref()

const onClickOutsideHandler = [
  (ev) => {
    console.log(ev)
    modal.value = false
  },
  { ignore: [ignoreElRef] }
]

</script>

<template>
  <button @click="modal = true">
    Open Modal
  </button>

  <div ref="ignoreElRef">
    click outside ignore element
  </div>

  <div v-if="modal" v-on-click-outside="onClickOutsideHandler">
    Hello World
  </div>
</template>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface OnClickOutsideOptions extends ConfigurableWindow {
  /**
   * List of elements that should not trigger the event.
   */
  ignore?: (MaybeElementRef | string)[]
  /**
   * Use capturing phase for internal event listener.
   * @default true
   */
  capture?: boolean
  /**
   * Run handler function if focus moves to an iframe.
   * @default false
   */
  detectIframe?: boolean
}
export type OnClickOutsideHandler<
  T extends {
    detectIframe: OnClickOutsideOptions["detectIframe"]
  } = {
    detectIframe: false
  }
> = (
  evt: T["detectIframe"] extends true ? PointerEvent | FocusEvent : PointerEvent
) => void
/**
 * Listen for clicks outside of an element.
 *
 * @see https://vueuse.org/onClickOutside
 * @param target
 * @param handler
 * @param options
 */
export declare function onClickOutside<T extends OnClickOutsideOptions>(
  target: MaybeElementRef,
  handler: OnClickOutsideHandler<{
    detectIframe: T["detectIframe"]
  }>,
  options?: T
): (() => void) | undefined
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/onClickOutside/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/onClickOutside/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/onClickOutside/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/onClickOutside/>

useEventListener
================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 467 B |
|  Last Changed  | last week |


Use EventListener with ease. Register using [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) on mounted, and [removeEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) automatically on unmounted.


Usage
-----




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

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


You can also pass a ref as the event target, [`useEventListener`](index) will unregister the previous event and register the new one when you change the target.




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

const element = ref<HTMLDivElement>()
useEventListener(element, 'keydown', (e) => {
  console.log(e.key)
})
```




```
<template>
  <div v-if="cond" ref="element">Div1</div>
  <div v-else ref="element">Div2</div>
</template>
```


You can also call the returned to unregister the listener.




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

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

cleanup() // This will unregister the listener.
```


Type Declarations
-----------------



Show Type Declarations

```
interface InferEventTarget<Events> {
  addEventListener(event: Events, fn?: any, options?: any): any
  removeEventListener(event: Events, fn?: any, options?: any): any
}
export type WindowEventName = keyof WindowEventMap
export type DocumentEventName = keyof DocumentEventMap
export interface GeneralEventListener<E = Event> {
  (evt: E): void
}
/**
 * Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
 *
 * Overload 1: Omitted Window target
 *
 * @see https://vueuse.org/useEventListener
 * @param event
 * @param listener
 * @param options
 */
export declare function useEventListener<E extends keyof WindowEventMap>(
  event: Arrayable<E>,
  listener: Arrayable<(this: Window, ev: WindowEventMap[E]) => any>,
  options?: MaybeRefOrGetter<boolean | AddEventListenerOptions>
): Fn
/**
 * Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
 *
 * Overload 2: Explicitly Window target
 *
 * @see https://vueuse.org/useEventListener
 * @param target
 * @param event
 * @param listener
 * @param options
 */
export declare function useEventListener<E extends keyof WindowEventMap>(
  target: Window,
  event: Arrayable<E>,
  listener: Arrayable<(this: Window, ev: WindowEventMap[E]) => any>,
  options?: MaybeRefOrGetter<boolean | AddEventListenerOptions>
): Fn
/**
 * Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
 *
 * Overload 3: Explicitly Document target
 *
 * @see https://vueuse.org/useEventListener
 * @param target
 * @param event
 * @param listener
 * @param options
 */
export declare function useEventListener<E extends keyof DocumentEventMap>(
  target: DocumentOrShadowRoot,
  event: Arrayable<E>,
  listener: Arrayable<(this: Document, ev: DocumentEventMap[E]) => any>,
  options?: MaybeRefOrGetter<boolean | AddEventListenerOptions>
): Fn
/**
 * Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
 *
 * Overload 4: Custom event target with event type infer
 *
 * @see https://vueuse.org/useEventListener
 * @param target
 * @param event
 * @param listener
 * @param options
 */
export declare function useEventListener<
  Names extends string,
  EventType = Event
>(
  target: InferEventTarget<Names>,
  event: Arrayable<Names>,
  listener: Arrayable<GeneralEventListener<EventType>>,
  options?: MaybeRefOrGetter<boolean | AddEventListenerOptions>
): Fn
/**
 * Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
 *
 * Overload 5: Custom event target fallback
 *
 * @see https://vueuse.org/useEventListener
 * @param target
 * @param event
 * @param listener
 * @param options
 */
export declare function useEventListener<EventType = Event>(
  target: MaybeRefOrGetter<EventTarget | null | undefined>,
  event: Arrayable<string>,
  listener: Arrayable<GeneralEventListener<EventType>>,
  options?: MaybeRefOrGetter<boolean | AddEventListenerOptions>
): Fn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useEventListener/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useEventListener/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useEventListener/>

useTitle
========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 905 B |
|  Last Changed  | last week |


Reactive document title.



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



Usage
-----




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

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


Set initial title immediately:




```
const title = useTitle('New Title')
```


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




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

const messages = ref(0)

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

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


Pass an optional template tag [Vue Meta Title Template](https://vue-meta.nuxtjs.org/guide/metainfo.html) to update the title to be injected into this template:




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



**WARNING**`observe` is incompatible with `titleTemplate`.



Type Declarations
-----------------




```
export type UseTitleOptionsBase =
  | {
      /**
       * Observe `document.title` changes using MutationObserve
       * Cannot be used together with `titleTemplate` option.
       *
       * @default false
       */
      observe?: boolean
    }
  | {
      /**
       * The template string to parse the title (e.g., '%s | My Website')
       * Cannot be used together with `observe` option.
       *
       * @default '%s'
       */
      titleTemplate?: MaybeRef<string> | ((title: string) => string)
    }
export type UseTitleOptions = ConfigurableDocument & UseTitleOptionsBase
export declare function useTitle(
  newTitle: ReadonlyRefOrGetter<string | null | undefined>,
  options?: UseTitleOptions
): ComputedRef<string | null | undefined>
export declare function useTitle(
  newTitle?: MaybeRef<string | null | undefined>,
  options?: UseTitleOptions
): Ref<string | null | undefined>
export type UseTitleReturn = ReturnType<typeof useTitle>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTitle/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTitle/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTitle/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTitle/>

useStorage
==========




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 1.99 kB |
|  Last Changed  | last week |
|  Related  | [`useColorMode`](../usecolormode/index)[`useDark`](../usedark/index)[`useLocalStorage`](../uselocalstorage/index)[`useSessionStorage`](../usesessionstorage/index)[`useStorageAsync`](../usestorageasync/index) |


Reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)/[SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)


Usage
-----



**TIP**When using with Nuxt 3, this functions will **NOT** be auto imported in favor of Nitro's built-in [`useStorage()`](https://nitro.unjs.io/guide/storage). Use explicit import if you want to use the function from VueUse.





```
import { useStorage } from '@vueuse/core'

// bind object
const state = useStorage('my-store', { hello: 'hi', greeting: 'Hello' })

// bind boolean
const flag = useStorage('my-flag', true) // returns Ref<boolean>

// bind number
const count = useStorage('my-count', 0) // returns Ref<number>

// bind string with SessionStorage
const id = useStorage('my-id', 'some-string-id', sessionStorage) // returns Ref<string>

// delete data from storage
state.value = null
```


Merge Defaults
--------------


By default, [`useStorage`](index) will use the value from storage if it presents and ignores the default value. Be aware that when you adding more properties to the default value, the key might be undefined if client's storage does not have that key.




```
localStorage.setItem('my-store', '{"hello": "hello"}')

const state = useStorage('my-store', { hello: 'hi', greeting: 'hello' }, localStorage)

console.log(state.value.greeting) // undefined, since the value is not presented in storage
```


To solve that, you can enable `mergeDefaults` option.




```
localStorage.setItem('my-store', '{"hello": "nihao"}')

const state = useStorage(
  'my-store',
  { hello: 'hi', greeting: 'hello' },
  localStorage,
  { mergeDefaults: true } // <--
)

console.log(state.hello) // 'nihao', from storage
console.log(state.greeting) // 'hello', from merged default value
```


When setting it to true, it will perform a **shallow merge** for objects. You can pass a function to perform custom merge (e.g. deep merge), for example:




```
const state = useStorage(
  'my-store',
  { hello: 'hi', greeting: 'hello' },
  localStorage,
  { mergeDefaults: (storageValue, defaults) => deepMerge(defaults, storageValue) } // <--
)
```


Custom Serialization
--------------------


By default, [`useStorage`](index) will smartly use the corresponding serializer based on the data type of provided default value. For example, `JSON.stringify` / `JSON.parse` will be used for objects, `Number.toString` / `parseFloat` for numbers, etc.


You can also provide your own serialization function to [`useStorage`](index)




```
import { useStorage } from '@vueuse/core'

useStorage(
  'key',
  {},
  undefined,
  {
    serializer: {
      read: (v: any) => v ? JSON.parse(v) : null,
      write: (v: any) => JSON.stringify(v),
    },
  },
)
```


Please note when you provide `null` as the default value, [`useStorage`](index) can't assume the data type from it. In this case, you can provide a custom serializer or reuse the built-in ones explicitly.




```
import { StorageSerializers, useStorage } from '@vueuse/core'

const objectLike = useStorage('key', null, undefined, { serializer: StorageSerializers.object })
objectLike.value = { foo: 'bar' }
```


Type Declarations
-----------------



Show Type Declarations

```
export interface Serializer<T> {
  read(raw: string): T
  write(value: T): string
}
export interface SerializerAsync<T> {
  read(raw: string): Awaitable<T>
  write(value: T): Awaitable<string>
}
export declare const StorageSerializers: Record<
  "boolean" | "object" | "number" | "any" | "string" | "map" | "set" | "date",
  Serializer<any>
>
export declare const customStorageEventName = "vueuse-storage"
export interface StorageEventLike {
  storageArea: StorageLike | null
  key: StorageEvent["key"]
  oldValue: StorageEvent["oldValue"]
  newValue: StorageEvent["newValue"]
}
export interface UseStorageOptions<T>
  extends ConfigurableEventFilter,
    ConfigurableWindow,
    ConfigurableFlush {
  /**
   * Watch for deep changes
   *
   * @default true
   */
  deep?: boolean
  /**
   * Listen to storage changes, useful for multiple tabs application
   *
   * @default true
   */
  listenToStorageChanges?: boolean
  /**
   * Write the default value to the storage when it does not exist
   *
   * @default true
   */
  writeDefaults?: boolean
  /**
   * Merge the default value with the value read from the storage.
   *
   * When setting it to true, it will perform a **shallow merge** for objects.
   * You can pass a function to perform custom merge (e.g. deep merge), for example:
   *
   * @default false
   */
  mergeDefaults?: boolean | ((storageValue: T, defaults: T) => T)
  /**
   * Custom data serialization
   */
  serializer?: Serializer<T>
  /**
   * On error callback
   *
   * Default log error to `console.error`
   */
  onError?: (error: unknown) => void
  /**
   * Use shallow ref as reference
   *
   * @default false
   */
  shallow?: boolean
}
export declare function useStorage(
  key: string,
  defaults: MaybeRefOrGetter<string>,
  storage?: StorageLike,
  options?: UseStorageOptions<string>
): RemovableRef<string>
export declare function useStorage(
  key: string,
  defaults: MaybeRefOrGetter<boolean>,
  storage?: StorageLike,
  options?: UseStorageOptions<boolean>
): RemovableRef<boolean>
export declare function useStorage(
  key: string,
  defaults: MaybeRefOrGetter<number>,
  storage?: StorageLike,
  options?: UseStorageOptions<number>
): RemovableRef<number>
export declare function useStorage<T>(
  key: string,
  defaults: MaybeRefOrGetter<T>,
  storage?: StorageLike,
  options?: UseStorageOptions<T>
): RemovableRef<T>
export declare function useStorage<T = unknown>(
  key: string,
  defaults: MaybeRefOrGetter<null>,
  storage?: StorageLike,
  options?: UseStorageOptions<T>
): RemovableRef<T>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useStorage/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useStorage/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useStorage/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useStorage/>

useRefHistory
=============




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 1.46 kB |
|  Last Changed  | 8 months ago |
|  Related  | [`useDebouncedRefHistory`](../usedebouncedrefhistory/index)[`useManualRefHistory`](../usemanualrefhistory/index)[`useThrottledRefHistory`](../usethrottledrefhistory/index) |


Track the change history of a ref, also provides undo and redo functionality


[Learn useRefHistory with this FREE video lesson from Vue School!](https://vueschool.io/lessons/ref-history-with-vueuse?friend=vueuse)Usage
-----




```
import { ref } from 'vue'
import { useRefHistory } from '@vueuse/core'

const counter = ref(0)
const { history, undo, redo } = useRefHistory(counter)
```


Internally, `watch` is used to trigger a history point when the ref value is modified. This means that history points are triggered asynchronously batching modifications in the same "tick".




```
counter.value += 1

await nextTick()
console.log(history.value)
/* [
  { snapshot: 1, timestamp: 1601912898062 },
  { snapshot: 0, timestamp: 1601912898061 }
] */
```


You can use `undo` to reset the ref value to the last history point.




```
console.log(counter.value) // 1
undo()
console.log(counter.value) // 0
```


### Objects / arrays


When working with objects or arrays, since changing their attributes does not change the reference, it will not trigger the committing. To track attribute changes, you would need to pass `deep: true`. It will create clones for each history record.




```
const state = ref({
  foo: 1,
  bar: 'bar',
})

const { history, undo, redo } = useRefHistory(state, {
  deep: true,
})

state.value.foo = 2

await nextTick()
console.log(history.value)
/* [
  { snapshot: { foo: 2, bar: 'bar' } },
  { snapshot: { foo: 1, bar: 'bar' } }
] */
```


#### Custom Clone Function


[`useRefHistory`](index) only embeds the minimal clone function `x => JSON.parse(JSON.stringify(x))`. To use a full featured or custom clone function, you can set up via the `dump` options.


For example, using [structuredClone](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone):




```
import { useRefHistory } from '@vueuse/core'

const refHistory = useRefHistory(target, { dump: structuredClone })
```


Or by using [lodash's `cloneDeep`](https://lodash.com/docs/4.17.15#cloneDeep):




```
import { cloneDeep } from 'lodash-es'
import { useRefHistory } from '@vueuse/core'

const refHistory = useRefHistory(target, { dump: cloneDeep })
```


Or a more lightweight [`klona`](https://github.com/lukeed/klona):




```
import { klona } from 'klona'
import { useRefHistory } from '@vueuse/core'

const refHistory = useRefHistory(target, { dump: klona })
```


#### Custom Dump and Parse Function


Instead of using the `clone` param, you can pass custom functions to control the serialization and parsing. In case you do not need history values to be objects, this can save an extra clone when undoing. It is also useful in case you want to have the snapshots already stringified to be saved to local storage for example.




```
import { useRefHistory } from '@vueuse/core'

const refHistory = useRefHistory(target, {
  dump: JSON.stringify,
  parse: JSON.parse,
})
```


### History Capacity


We will keep all the history by default (unlimited) until you explicitly clear them up, you can set the maximal amount of history to be kept by `capacity` options.




```
const refHistory = useRefHistory(target, {
  capacity: 15, // limit to 15 history records
})

refHistory.clear() // explicitly clear all the history
```


### History Flush Timing


From [Vue's documentation](https://vuejs.org/guide/essentials/watchers.html#callback-flush-timing): Vue's reactivity system buffers invalidated effects and flush them asynchronously to avoid unnecessary duplicate invocation when there are many state mutations happening in the same "tick".


In the same way as `watch`, you can modify the flush timing using the `flush` option.




```
const refHistory = useRefHistory(target, {
  flush: 'sync', // options 'pre' (default), 'post' and 'sync'
})
```


The default is `'pre'`, to align this composable with the default for Vue's watchers. This also helps to avoid common issues, like several history points generated as part of a multi-step update to a ref value that can break invariants of the app state. You can use `commit()` in case you need to create multiple history points in the same "tick"




```
const r = ref(0)
const { history, commit } = useRefHistory(r)

r.value = 1
commit()

r.value = 2
commit()

console.log(history.value)
/* [
  { snapshot: 2 },
  { snapshot: 1 },
  { snapshot: 0 },
] */
```


On the other hand, when using flush `'sync'`, you can use `batch(fn)` to generate a single history point for several sync operations




```
const r = ref({ names: [], version: 1 })
const { history, batch } = useRefHistory(r, { flush: 'sync' })

batch(() => {
  r.names.push('Lena')
  r.version++
})

console.log(history.value)
/* [
  { snapshot: { names: [ 'Lena' ], version: 2 },
  { snapshot: { names: [], version: 1 },
] */
```


If `{ flush: 'sync', deep: true }` is used, `batch` is also useful when doing a mutable `splice` in an array. `splice` can generate up to three atomic operations that will be pushed to the ref history.




```
const arr = ref([1, 2, 3])
const { history, batch } = useRefHistory(r, { deep: true, flush: 'sync' })

batch(() => {
  arr.value.splice(1, 1) // batch ensures only one history point is generated
})
```


Another option is to avoid mutating the original ref value using `arr.value = [...arr.value].splice(1,1)`.


Recommended Readings
--------------------


* [History and Persistence](https://patak.dev/vue/history-and-persistence.html) - by [@matias-capeletto](https://github.com/matias-capeletto)


Type Declarations
-----------------



Show Type Declarations

```
export interface UseRefHistoryOptions<Raw, Serialized = Raw>
  extends ConfigurableEventFilter {
  /**
   * Watch for deep changes, default to false
   *
   * When set to true, it will also create clones for values store in the history
   *
   * @default false
   */
  deep?: boolean
  /**
   * The flush option allows for greater control over the timing of a history point, default to 'pre'
   *
   * Possible values: 'pre', 'post', 'sync'
   * It works in the same way as the flush option in watch and watch effect in vue reactivity
   *
   * @default 'pre'
   */
  flush?: "pre" | "post" | "sync"
  /**
   * Maximum number of history to be kept. Default to unlimited.
   */
  capacity?: number
  /**
   * Clone when taking a snapshot, shortcut for dump: JSON.parse(JSON.stringify(value)).
   * Default to false
   *
   * @default false
   */
  clone?: boolean | CloneFn<Raw>
  /**
   * Serialize data into the history
   */
  dump?: (v: Raw) => Serialized
  /**
   * Deserialize data from the history
   */
  parse?: (v: Serialized) => Raw
}
export interface UseRefHistoryReturn<Raw, Serialized>
  extends UseManualRefHistoryReturn<Raw, Serialized> {
  /**
   * A ref representing if the tracking is enabled
   */
  isTracking: Ref<boolean>
  /**
   * Pause change tracking
   */
  pause(): void
  /**
   * Resume change tracking
   *
   * @param [commit] if true, a history record will be create after resuming
   */
  resume(commit?: boolean): void
  /**
   * A sugar for auto pause and auto resuming within a function scope
   *
   * @param fn
   */
  batch(fn: (cancel: Fn) => void): void
  /**
   * Clear the data and stop the watch
   */
  dispose(): void
}
/**
 * Track the change history of a ref, also provides undo and redo functionality.
 *
 * @see https://vueuse.org/useRefHistory
 * @param source
 * @param options
 */
export declare function useRefHistory<Raw, Serialized = Raw>(
  source: Ref<Raw>,
  options?: UseRefHistoryOptions<Raw, Serialized>
): UseRefHistoryReturn<Raw, Serialized>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useRefHistory/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useRefHistory/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useRefHistory/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useRefHistory/>

syncRef
=======




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 237 B |
|  Last Changed  | 9 months ago |
|  Related  | [`syncRefs`](../syncrefs/index) |


Two-way refs synchronization.


Usage
-----




```
import { syncRef } from '@vueuse/core'

const a = ref('a')
const b = ref('b')

const stop = syncRef(a, b)

console.log(a.value) // a

b.value = 'foo'

console.log(a.value) // foo

a.value = 'bar'

console.log(b.value) // bar
```


### One directional




```
import { syncRef } from '@vueuse/core'

const a = ref('a')
const b = ref('b')

const stop = syncRef(a, b, { direction: 'rtl' })
```


### Custom Transform




```
import { syncRef } from '@vueuse/core'

const a = ref(10)
const b = ref(2)

const stop = syncRef(a, b, {
  transform: {
    ltr: left => left * 2,
    rtl: right => right / 2
  }
})

console.log(b.value) // 20

b.value = 30

console.log(a.value) // 15
```


Type Declarations
-----------------




```
export interface SyncRefOptions<L, R = L> extends ConfigurableFlushSync {
  /**
   * Watch deeply
   *
   * @default false
   */
  deep?: boolean
  /**
   * Sync values immediately
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Direction of syncing. Value will be redefined if you define syncConvertors
   *
   * @default 'both'
   */
  direction?: "ltr" | "rtl" | "both"
  /**
   * Custom transform function
   */
  transform?: {
    ltr?: (left: L) => R
    rtl?: (right: R) => L
  }
}
/**
 * Two-way refs synchronization.
 *
 * @param left
 * @param right
 */
export declare function syncRef<L, R = L>(
  left: Ref<L>,
  right: Ref<R>,
  options?: SyncRefOptions<L, R>
): () => void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/syncRef/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/syncRef/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/syncRef/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/syncRef/>

tryOnUnmounted
==============




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 85 B |
|  Last Changed  | last year |


Safe `onUnmounted`. Call `onUnmounted()` if it's inside a component lifecycle, if not, do nothing


Usage
-----




```
import { tryOnUnmounted } from '@vueuse/core'

tryOnUnmounted(() => {

})
```


Type Declarations
-----------------




```
/**
 * Call onUnmounted() if it's inside a component lifecycle, if not, do nothing
 *
 * @param fn
 */
export declare function tryOnUnmounted(fn: Fn): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnUnmounted/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnUnmounted/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/tryOnUnmounted/>

watchDebounced
==============




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 786 B |
|  Last Changed  | 2 weeks ago |
|  Alias  | `debouncedWatch` |


Debounced watch


Usage
-----


Similar to `watch`, but offering extra options `debounce` and `maxWait` which will be applied to the callback function.




```
import { watchDebounced } from '@vueuse/core'

watchDebounced(
  source,
  () => { console.log('changed!') },
  { debounce: 500, maxWait: 1000 },
)
```


It's essentially a shorthand for the following code:




```
import { debounceFilter, watchWithFilter } from '@vueuse/core'

watchWithFilter(
  source,
  () => { console.log('changed!') },
  {
    eventFilter: debounceFilter(500, { maxWait: 1000 }),
  },
)
```


Type Declarations
-----------------




```
export interface WatchDebouncedOptions<Immediate>
  extends WatchOptions<Immediate>,
    DebounceFilterOptions {
  debounce?: MaybeRefOrGetter<number>
}
export declare function watchDebounced<
  T extends Readonly<WatchSource<unknown>[]>,
  Immediate extends Readonly<boolean> = false
>(
  sources: [...T],
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options?: WatchDebouncedOptions<Immediate>
): WatchStopHandle
export declare function watchDebounced<
  T,
  Immediate extends Readonly<boolean> = false
>(
  source: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchDebouncedOptions<Immediate>
): WatchStopHandle
export declare function watchDebounced<
  T extends object,
  Immediate extends Readonly<boolean> = false
>(
  source: T,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchDebouncedOptions<Immediate>
): WatchStopHandle
export { watchDebounced as debouncedWatch }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchDebounced/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchDebounced/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchDebounced/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchDebounced/>

useInterval
===========




|  |  |
| --- | --- |
|  Category  | [Animation](../../functions#category=Animation) |
|  Export Size  | 620 B |
|  Last Changed  | 2 weeks ago |


Reactive counter increases on every interval


Usage
-----




```
import { useInterval } from '@vueuse/core'

// count will increase every 200ms
const counter = useInterval(200)
```




```
const { counter, reset, pause, resume } = useInterval(200, { controls: true })
```


Type Declarations
-----------------




```
export interface UseIntervalOptions<Controls extends boolean> {
  /**
   * Expose more controls
   *
   * @default false
   */
  controls?: Controls
  /**
   * Execute the update immediately on calling
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Callback on every interval
   */
  callback?: (count: number) => void
}
export interface UseIntervalControls {
  counter: Ref<number>
  reset: () => void
}
/**
 * Reactive counter increases on every interval
 *
 * @see https://vueuse.org/useInterval
 * @param interval
 * @param options
 */
export declare function useInterval(
  interval?: MaybeRefOrGetter<number>,
  options?: UseIntervalOptions<false>
): Ref<number>
export declare function useInterval(
  interval: MaybeRefOrGetter<number>,
  options: UseIntervalOptions<true>
): UseIntervalControls & Pausable
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useInterval/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useInterval/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useInterval/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useInterval/>

useRafFn
========




|  |  |
| --- | --- |
|  Category  | [Animation](../../functions#category=Animation) |
|  Export Size  | 342 B |
|  Last Changed  | 3 months ago |


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


Usage
-----




```
import { ref } from 'vue'
import { useRafFn } from '@vueuse/core'

const count = ref(0)

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


Type Declarations
-----------------




```
export interface UseRafFnCallbackArguments {
  /**
   * Time elapsed between this and the last frame.
   */
  delta: number
  /**
   * Time elapsed since the creation of the web page. See {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin Time origin}.
   */
  timestamp: DOMHighResTimeStamp
}
export interface UseRafFnOptions extends ConfigurableWindow {
  /**
   * Start the requestAnimationFrame loop immediately on creation
   *
   * @default true
   */
  immediate?: boolean
}
/**
 * Call function on every `requestAnimationFrame`. With controls of pausing and resuming.
 *
 * @see https://vueuse.org/useRafFn
 * @param fn
 * @param options
 */
export declare function useRafFn(
  fn: (args: UseRafFnCallbackArguments) => void,
  options?: UseRafFnOptions
): Pausable
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useRafFn/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useRafFn/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useRafFn/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useRafFn/>

useTimestamp
============




|  |  |
| --- | --- |
|  Category  | [Animation](../../functions#category=Animation) |
|  Export Size  | 817 B |
|  Last Changed  | 7 months ago |


Reactive current timestamp


Usage
-----




```
import { useTimestamp } from '@vueuse/core'

const timestamp = useTimestamp({ offset: 0 })
```




```
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](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export interface UseTimestampOptions<Controls extends boolean> {
  /**
   * Expose more controls
   *
   * @default false
   */
  controls?: Controls
  /**
   * Offset value adding to the value
   *
   * @default 0
   */
  offset?: number
  /**
   * Update the timestamp immediately
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Update interval, or use requestAnimationFrame
   *
   * @default requestAnimationFrame
   */
  interval?: "requestAnimationFrame" | number
  /**
   * Callback on each update
   */
  callback?: (timestamp: number) => void
}
/**
 * Reactive current timestamp.
 *
 * @see https://vueuse.org/useTimestamp
 * @param options
 */
export declare function useTimestamp(
  options?: UseTimestampOptions<false>
): Ref<number>
export declare function useTimestamp(options: UseTimestampOptions<true>): {
  timestamp: Ref<number>
} & Pausable
export type UseTimestampReturn = ReturnType<typeof useTimestamp>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTimestamp/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTimestamp/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTimestamp/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTimestamp/>

useShare
========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 546 B |
|  Last Changed  | 2 weeks ago |


Reactive [Web Share API](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share). The Browser provides features that can share content in text or file.



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


Usage
-----




```
import { useShare } from '@vueuse/core'

const { share, isSupported } = useShare()

function startShare() {
  share({
    title: 'Hello',
    text: 'Hello my friend!',
    url: location.href,
  })
}
```


### Passing a source ref


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




```
import { ref } from 'vue'

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

shareOptions.value.text = 'bar'

share()
```


Type Declarations
-----------------




```
export interface UseShareOptions {
  title?: string
  files?: File[]
  text?: string
  url?: string
}
/**
 * Reactive Web Share API.
 *
 * @see https://vueuse.org/useShare
 * @param shareOptions
 * @param options
 */
export declare function useShare(
  shareOptions?: MaybeRefOrGetter<UseShareOptions>,
  options?: ConfigurableNavigator
): {
  isSupported: ComputedRef<boolean>
  share: (overrideOptions?: MaybeRefOrGetter<UseShareOptions>) => Promise<void>
}
export type UseShareReturn = ReturnType<typeof useShare>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useShare/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useShare/demo.client.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useShare/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useShare/>

useMediaControls
================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 2.36 kB |
|  Last Changed  | 4 days ago |


Reactive media controls for both `audio` and `video` elements


Usage
-----


### Basic Usage




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

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

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

<template>
  <video ref="video" />
  <button @click="playing = !playing">Play / Pause</button>
  <span>{{ currentTime }} / {{ duration }}</span>
</template>
```


### Providing Captions, Subtitles, etc...


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




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

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


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Many of the jsdoc definitions here are modified version of the
 * documentation from MDN(https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement)
 */
export interface UseMediaSource {
  /**
   * The source url for the media
   */
  src: string
  /**
   * The media codec type
   */
  type?: string
}
export interface UseMediaTextTrackSource {
  /**
   * Indicates that the track should be enabled unless the user's preferences indicate
   * that another track is more appropriate
   */
  default?: boolean
  /**
   * How the text track is meant to be used. If omitted the default kind is subtitles.
   */
  kind: TextTrackKind
  /**
   * A user-readable title of the text track which is used by the browser
   * when listing available text tracks.
   */
  label: string
  /**
   * Address of the track (.vtt file). Must be a valid URL. This attribute
   * must be specified and its URL value must have the same origin as the document
   */
  src: string
  /**
   * Language of the track text data. It must be a valid BCP 47 language tag.
   * If the kind attribute is set to subtitles, then srclang must be defined.
   */
  srcLang: string
}
interface UseMediaControlsOptions extends ConfigurableDocument {
  /**
   * The source for the media, may either be a string, a `UseMediaSource` object, or a list
   * of `UseMediaSource` objects.
   */
  src?: MaybeRefOrGetter<string | UseMediaSource | UseMediaSource[]>
  /**
   * A list of text tracks for the media
   */
  tracks?: MaybeRefOrGetter<UseMediaTextTrackSource[]>
}
export interface UseMediaTextTrack {
  /**
   * The index of the text track
   */
  id: number
  /**
   * The text track label
   */
  label: string
  /**
   * Language of the track text data. It must be a valid BCP 47 language tag.
   * If the kind attribute is set to subtitles, then srclang must be defined.
   */
  language: string
  /**
   * Specifies the display mode of the text track, either `disabled`,
   * `hidden`, or `showing`
   */
  mode: TextTrackMode
  /**
   * How the text track is meant to be used. If omitted the default kind is subtitles.
   */
  kind: TextTrackKind
  /**
   * Indicates the track's in-band metadata track dispatch type.
   */
  inBandMetadataTrackDispatchType: string
  /**
   * A list of text track cues
   */
  cues: TextTrackCueList | null
  /**
   * A list of active text track cues
   */
  activeCues: TextTrackCueList | null
}
export declare function useMediaControls(
  target: MaybeRef<HTMLMediaElement | null | undefined>,
  options?: UseMediaControlsOptions
): {
  currentTime: Ref<number>
  duration: Ref<number>
  waiting: Ref<boolean>
  seeking: Ref<boolean>
  ended: Ref<boolean>
  stalled: Ref<boolean>
  buffered: Ref<[number, number][]>
  playing: Ref<boolean>
  rate: Ref<number>
  volume: Ref<number>
  muted: Ref<boolean>
  tracks: Ref<
    {
      id: number
      label: string
      language: string
      mode: TextTrackMode
      kind: TextTrackKind
      inBandMetadataTrackDispatchType: string
      cues: {
        [x: number]: {
          endTime: number
          id: string
          onenter: ((this: TextTrackCue, ev: Event) => any) | null
          onexit: ((this: TextTrackCue, ev: Event) => any) | null
          pauseOnExit: boolean
          startTime: number
          readonly track: {
            readonly activeCues: any | null
            readonly cues: any | null
            readonly id: string
            readonly inBandMetadataTrackDispatchType: string
            readonly kind: TextTrackKind
            readonly label: string
            readonly language: string
            mode: TextTrackMode
            oncuechange: ((this: TextTrack, ev: Event) => any) | null
            addCue: (cue: TextTrackCue) => void
            removeCue: (cue: TextTrackCue) => void
            addEventListener: {
              <K extends "cuechange">(
                type: K,
                listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any,
                options?: boolean | AddEventListenerOptions | undefined
              ): void
              (
                type: string,
                listener: EventListenerOrEventListenerObject,
                options?: boolean | AddEventListenerOptions | undefined
              ): void
            }
            removeEventListener: {
              <K_1 extends "cuechange">(
                type: K_1,
                listener: (this: TextTrack, ev: TextTrackEventMap[K_1]) => any,
                options?: boolean | EventListenerOptions | undefined
              ): void
              (
                type: string,
                listener: EventListenerOrEventListenerObject,
                options?: boolean | EventListenerOptions | undefined
              ): void
            }
            dispatchEvent: (event: Event) => boolean
          } | null
          addEventListener: {
            <K_2 extends keyof TextTrackCueEventMap>(
              type: K_2,
              listener: (
                this: TextTrackCue,
                ev: TextTrackCueEventMap[K_2]
              ) => any,
              options?: boolean | AddEventListenerOptions | undefined
            ): void
            (
              type: string,
              listener: EventListenerOrEventListenerObject,
              options?: boolean | AddEventListenerOptions | undefined
            ): void
          }
          removeEventListener: {
            <K_3 extends keyof TextTrackCueEventMap>(
              type: K_3,
              listener: (
                this: TextTrackCue,
                ev: TextTrackCueEventMap[K_3]
              ) => any,
              options?: boolean | EventListenerOptions | undefined
            ): void
            (
              type: string,
              listener: EventListenerOrEventListenerObject,
              options?: boolean | EventListenerOptions | undefined
            ): void
          }
          dispatchEvent: (event: Event) => boolean
        }
        readonly length: number
        getCueById: (id: string) => TextTrackCue | null
        [Symbol.iterator]: () => IterableIterator<TextTrackCue>
      } | null
      activeCues: {
        [x: number]: {
          endTime: number
          id: string
          onenter: ((this: TextTrackCue, ev: Event) => any) | null
          onexit: ((this: TextTrackCue, ev: Event) => any) | null
          pauseOnExit: boolean
          startTime: number
          readonly track: {
            readonly activeCues: any | null
            readonly cues: any | null
            readonly id: string
            readonly inBandMetadataTrackDispatchType: string
            readonly kind: TextTrackKind
            readonly label: string
            readonly language: string
            mode: TextTrackMode
            oncuechange: ((this: TextTrack, ev: Event) => any) | null
            addCue: (cue: TextTrackCue) => void
            removeCue: (cue: TextTrackCue) => void
            addEventListener: {
              <K extends "cuechange">(
                type: K,
                listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any,
                options?: boolean | AddEventListenerOptions | undefined
              ): void
              (
                type: string,
                listener: EventListenerOrEventListenerObject,
                options?: boolean | AddEventListenerOptions | undefined
              ): void
            }
            removeEventListener: {
              <K_1 extends "cuechange">(
                type: K_1,
                listener: (this: TextTrack, ev: TextTrackEventMap[K_1]) => any,
                options?: boolean | EventListenerOptions | undefined
              ): void
              (
                type: string,
                listener: EventListenerOrEventListenerObject,
                options?: boolean | EventListenerOptions | undefined
              ): void
            }
            dispatchEvent: (event: Event) => boolean
          } | null
          addEventListener: {
            <K_2 extends keyof TextTrackCueEventMap>(
              type: K_2,
              listener: (
                this: TextTrackCue,
                ev: TextTrackCueEventMap[K_2]
              ) => any,
              options?: boolean | AddEventListenerOptions | undefined
            ): void
            (
              type: string,
              listener: EventListenerOrEventListenerObject,
              options?: boolean | AddEventListenerOptions | undefined
            ): void
          }
          removeEventListener: {
            <K_3 extends keyof TextTrackCueEventMap>(
              type: K_3,
              listener: (
                this: TextTrackCue,
                ev: TextTrackCueEventMap[K_3]
              ) => any,
              options?: boolean | EventListenerOptions | undefined
            ): void
            (
              type: string,
              listener: EventListenerOrEventListenerObject,
              options?: boolean | EventListenerOptions | undefined
            ): void
          }
          dispatchEvent: (event: Event) => boolean
        }
        readonly length: number
        getCueById: (id: string) => TextTrackCue | null
        [Symbol.iterator]: () => IterableIterator<TextTrackCue>
      } | null
    }[]
  >
  selectedTrack: Ref<number>
  enableTrack: (
    track: number | UseMediaTextTrack,
    disableTracks?: boolean
  ) => void
  disableTrack: (track?: number | UseMediaTextTrack) => void
  supportsPictureInPicture: boolean | undefined
  togglePictureInPicture: () => Promise<unknown>
  isPictureInPicture: Ref<boolean>
  onSourceError: EventHookOn<Event>
}
export type UseMediaControlsReturn = ReturnType<typeof useMediaControls>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMediaControls/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMediaControls/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMediaControls/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMediaControls/>

useFetch
========




|  |  |
| --- | --- |
|  Category  | [Network](../../functions#category=Network) |
|  Export Size  | 2.42 kB |
|  Last Changed  | 2 weeks ago |


Reactive [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provides the ability to abort requests, intercept requests before they are fired, automatically refetch requests when the url changes, and create your own [`useFetch`](index) with predefined options.


[Learn useFetch with this FREE video lesson from Vue School!](https://vueschool.io/lessons/vueuse-utilities-usefetch-and-reactify?friend=vueuse)
**TIP**When using with Nuxt 3, this functions will **NOT** be auto imported in favor of Nuxt's built-in [`useFetch()`](https://v3.nuxtjs.org/api/composables/use-fetch). Use explicit import if you want to use the function from VueUse.



Usage
-----


### Basic Usage


The [`useFetch`](index) function can be used by simply providing a url. The url can be either a string or a `ref`. The `data` object will contain the result of the request, the `error` object will contain any errors, and the `isFetching` object will indicate if the request is loading.




```
import { useFetch } from '@vueuse/core'

const { isFetching, error, data } = useFetch(url)
```


### Asynchronous Usage


[`useFetch`](index) can also be awaited just like a normal fetch. Note that whenever a component is asynchronous, whatever component that uses it must wrap the component in a `<Suspense>` tag. You can read more about the suspense api in the [Offical Vue 3 Docs](https://vuejs.org/guide/built-ins/suspense.html)




```
import { useFetch } from '@vueuse/core'

const { isFetching, error, data } = await useFetch(url)
```


### Refetching on URL change


Using a `ref` for the url parameter will allow the [`useFetch`](index) function to automatically trigger another request when the url is changed.




```
const url = ref('https://my-api.com/user/1')

const { data } = useFetch(url, { refetch: true })

url.value = 'https://my-api.com/user/2' // Will trigger another request
```


### Prevent request from firing immediately


Setting the `immediate` option to false will prevent the request from firing until the `execute` function is called.




```
const { execute } = useFetch(url, { immediate: false })

execute()
```


### Aborting a request


A request can be aborted by using the `abort` function from the [`useFetch`](index) function. The `canAbort` property indicates if the request can be aborted.




```
const { abort, canAbort } = useFetch(url)

setTimeout(() => {
  if (canAbort.value)
    abort()
}, 100)
```


A request can also be aborted automatically by using `timeout` property. It will call `abort` function when the given timeout is reached.




```
const { data } = useFetch(url, { timeout: 100 })
```


### Intercepting a request


The `beforeFetch` option can intercept a request before it is sent and modify the request options and url.




```
const { data } = useFetch(url, {
  async beforeFetch({ url, options, cancel }) {
    const myToken = await getMyToken()

    if (!myToken)
      cancel()

    options.headers = {
      ...options.headers,
      Authorization: `Bearer ${myToken}`,
    }

    return {
      options,
    }
  },
})
```


The `afterFetch` option can intercept the response data before it is updated.




```
const { data } = useFetch(url, {
  afterFetch(ctx) {
    if (ctx.data.title === 'HxH')
      ctx.data.title = 'Hunter x Hunter' // Modifies the response data

    return ctx
  },
})
```


The `onFetchError` option can intercept the response data and error before it is updated.




```
const { data } = useFetch(url, {
  onFetchError(ctx) {
    // ctx.data can be null when 5xx response
    if (ctx.data === null)
      ctx.data = { title: 'Hunter x Hunter' } // Modifies the response data

    ctx.error = new Error('Custom Error') // Modifies the error

    return ctx
  },
})
```


### Setting the request method and return type


The request method and return type can be set by adding the appropriate methods to the end of `useFetch`




```
// Request will be sent with GET method and data will be parsed as JSON
const { data } = useFetch(url).get().json()

// Request will be sent with POST method and data will be parsed as text
const { data } = useFetch(url).post().text()

// Or set the method using the options

// Request will be sent with GET method and data will be parsed as blob
const { data } = useFetch(url, { method: 'GET' }, { refetch: true }).blob()
```


### Creating a Custom Instance


The `createFetch` function will return a useFetch function with whatever pre-configured options that are provided to it. This is useful for interacting with API's throughout an application that uses the same base URL or needs Authorization headers.




```
const useMyFetch = createFetch({
  baseUrl: 'https://my-api.com',
  options: {
    async beforeFetch({ options }) {
      const myToken = await getMyToken()
      options.headers.Authorization = `Bearer ${myToken}`

      return { options }
    },
  },
  fetchOptions: {
    mode: 'cors',
  },
})

const { isFetching, error, data } = useMyFetch('users')
```


If you want to control the behavior of `beforeFetch`, `afterFetch`, `onFetchError` between the pre-configured instance and newly spawned instance. You can provide a `combination` option to toggle between `overwrite` or `chaining`.




```
const useMyFetch = createFetch({
  baseUrl: 'https://my-api.com',
  combination: 'overwrite',
  options: {
    // beforeFetch in pre-configured instance will only run when the newly spawned instance do not pass beforeFetch
    async beforeFetch({ options }) {
      const myToken = await getMyToken()
      options.headers.Authorization = `Bearer ${myToken}`

      return { options }
    },
  },
})

// use useMyFetch beforeFetch
const { isFetching, error, data } = useMyFetch('users')

// use custom beforeFetch
const { isFetching, error, data } = useMyFetch('users', {
  async beforeFetch({ url, options, cancel }) {
    const myToken = await getMyToken()

    if (!myToken)
      cancel()

    options.headers = {
      ...options.headers,
      Authorization: `Bearer ${myToken}`,
    }

    return {
      options,
    }
  },
})
```


### Events


The `onFetchResponse` and `onFetchError` will fire on fetch request responses and errors respectively.




```
const { onFetchResponse, onFetchError } = useFetch(url)

onFetchResponse((response) => {
  console.log(response.status)
})

onFetchError((error) => {
  console.error(error.message)
})
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseFetchReturn<T> {
  /**
   * Indicates if the fetch request has finished
   */
  isFinished: Ref<boolean>
  /**
   * The statusCode of the HTTP fetch response
   */
  statusCode: Ref<number | null>
  /**
   * The raw response of the fetch response
   */
  response: Ref<Response | null>
  /**
   * Any fetch errors that may have occurred
   */
  error: Ref<any>
  /**
   * The fetch response body on success, may either be JSON or text
   */
  data: Ref<T | null>
  /**
   * Indicates if the request is currently being fetched.
   */
  isFetching: Ref<boolean>
  /**
   * Indicates if the fetch request is able to be aborted
   */
  canAbort: ComputedRef<boolean>
  /**
   * Indicates if the fetch request was aborted
   */
  aborted: Ref<boolean>
  /**
   * Abort the fetch request
   */
  abort: Fn
  /**
   * Manually call the fetch
   * (default not throwing error)
   */
  execute: (throwOnFailed?: boolean) => Promise<any>
  /**
   * Fires after the fetch request has finished
   */
  onFetchResponse: EventHookOn<Response>
  /**
   * Fires after a fetch request error
   */
  onFetchError: EventHookOn
  /**
   * Fires after a fetch has completed
   */
  onFetchFinally: EventHookOn
  get(): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  post(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  put(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  delete(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  patch(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  head(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  options(
    payload?: MaybeRefOrGetter<unknown>,
    type?: string
  ): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
  json<JSON = any>(): UseFetchReturn<JSON> & PromiseLike<UseFetchReturn<JSON>>
  text(): UseFetchReturn<string> & PromiseLike<UseFetchReturn<string>>
  blob(): UseFetchReturn<Blob> & PromiseLike<UseFetchReturn<Blob>>
  arrayBuffer(): UseFetchReturn<ArrayBuffer> &
    PromiseLike<UseFetchReturn<ArrayBuffer>>
  formData(): UseFetchReturn<FormData> & PromiseLike<UseFetchReturn<FormData>>
}
type Combination = "overwrite" | "chain"
export interface BeforeFetchContext {
  /**
   * The computed url of the current request
   */
  url: string
  /**
   * The request options of the current request
   */
  options: RequestInit
  /**
   * Cancels the current request
   */
  cancel: Fn
}
export interface AfterFetchContext<T = any> {
  response: Response
  data: T | null
}
export interface OnFetchErrorContext<T = any, E = any> {
  error: E
  data: T | null
}
export interface UseFetchOptions {
  /**
   * Fetch function
   */
  fetch?: typeof window.fetch
  /**
   * Will automatically run fetch when `useFetch` is used
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Will automatically refetch when:
   * - the URL is changed if the URL is a ref
   * - the payload is changed if the payload is a ref
   *
   * @default false
   */
  refetch?: MaybeRefOrGetter<boolean>
  /**
   * Initial data before the request finished
   *
   * @default null
   */
  initialData?: any
  /**
   * Timeout for abort request after number of millisecond
   * `0` means use browser default
   *
   * @default 0
   */
  timeout?: number
  /**
   * Will run immediately before the fetch request is dispatched
   */
  beforeFetch?: (
    ctx: BeforeFetchContext
  ) =>
    | Promise<Partial<BeforeFetchContext> | void>
    | Partial<BeforeFetchContext>
    | void
  /**
   * Will run immediately after the fetch request is returned.
   * Runs after any 2xx response
   */
  afterFetch?: (
    ctx: AfterFetchContext
  ) => Promise<Partial<AfterFetchContext>> | Partial<AfterFetchContext>
  /**
   * Will run immediately after the fetch request is returned.
   * Runs after any 4xx and 5xx response
   */
  onFetchError?: (ctx: {
    data: any
    response: Response | null
    error: any
  }) => Promise<Partial<OnFetchErrorContext>> | Partial<OnFetchErrorContext>
}
export interface CreateFetchOptions {
  /**
   * The base URL that will be prefixed to all urls unless urls are absolute
   */
  baseUrl?: MaybeRefOrGetter<string>
  /**
   * Determine the inherit behavior for beforeFetch, afterFetch, onFetchError
   * @default 'chain'
   */
  combination?: Combination
  /**
   * Default Options for the useFetch function
   */
  options?: UseFetchOptions
  /**
   * Options for the fetch request
   */
  fetchOptions?: RequestInit
}
export declare function createFetch(
  config?: CreateFetchOptions
): typeof useFetch
export declare function useFetch<T>(
  url: MaybeRefOrGetter<string>
): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
export declare function useFetch<T>(
  url: MaybeRefOrGetter<string>,
  useFetchOptions: UseFetchOptions
): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
export declare function useFetch<T>(
  url: MaybeRefOrGetter<string>,
  options: RequestInit,
  useFetchOptions?: UseFetchOptions
): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useFetch/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useFetch/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useFetch/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useFetch/>

useDark
=======




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 3.03 kB |
|  Last Changed  | 2 days ago |
|  Related  | [`useColorMode`](../usecolormode/index)[`usePreferredDark`](../usepreferreddark/index)[`useStorage`](../usestorage/index) |


Reactive dark mode with auto data persistence.


[Learn useDark with this FREE video lesson from Vue School!](https://vueschool.io/lessons/theming-with-vueuse-usedark-and-usecolormode?friend=vueuse)Basic Usage
-----------




```
import { useDark, useToggle } from '@vueuse/core'

const isDark = useDark()
const toggleDark = useToggle(isDark)
```


Behavior
--------


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



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


Configuration
-------------


By default, it uses [Tailwind CSS favored dark mode](https://tailwindcss.com/docs/dark-mode#toggling-dark-mode-manually), which enables dark mode when class `dark` is applied to the `html` tag, for example:




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

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


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


For example:




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


will work like




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

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


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




```
const isDark = useDark({
  onChanged(dark: boolean) {
    // update the dom, call the API or something
  },
})
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export interface UseDarkOptions
  extends Omit<UseColorModeOptions<BasicColorSchema>, "modes" | "onChanged"> {
  /**
   * Value applying to the target element when isDark=true
   *
   * @default 'dark'
   */
  valueDark?: string
  /**
   * Value applying to the target element when isDark=false
   *
   * @default ''
   */
  valueLight?: string
  /**
   * A custom handler for handle the updates.
   * When specified, the default behavior will be overridden.
   *
   * @default undefined
   */
  onChanged?: (
    isDark: boolean,
    defaultHandler: (mode: BasicColorSchema) => void,
    mode: BasicColorSchema
  ) => void
}
/**
 * Reactive dark mode with auto data persistence.
 *
 * @see https://vueuse.org/useDark
 * @param options
 */
export declare function useDark(
  options?: UseDarkOptions
): WritableComputedRef<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDark/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDark/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDark/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDark/>

useColorMode
============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 2.88 kB |
|  Last Changed  | 2 days ago |
|  Related  | [`useDark`](../usedark/index)[`usePreferredDark`](../usepreferreddark/index)[`useStorage`](../usestorage/index) |


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


Basic Usage
-----------




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

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


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




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

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

mode.value = 'auto' // change to auto mode
```


Config
------




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

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


Advanced Usage
--------------


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




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

const { system, store } = useColorMode()

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

const myColorMode = computed(() => store.value === 'auto' ? system.value : store.value)
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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


Type Declarations
-----------------



Show Type Declarations

```
export type BasicColorMode = "light" | "dark"
export type BasicColorSchema = BasicColorMode | "auto"
export interface UseColorModeOptions<T extends string = BasicColorMode>
  extends UseStorageOptions<T | BasicColorMode> {
  /**
   * CSS Selector for the target element applying to
   *
   * @default 'html'
   */
  selector?: string | MaybeElementRef
  /**
   * HTML attribute applying the target element
   *
   * @default 'class'
   */
  attribute?: string
  /**
   * The initial color mode
   *
   * @default 'auto'
   */
  initialValue?: MaybeRefOrGetter<T | BasicColorSchema>
  /**
   * Prefix when adding value to the attribute
   */
  modes?: Partial<Record<T | BasicColorSchema, string>>
  /**
   * A custom handler for handle the updates.
   * When specified, the default behavior will be overridden.
   *
   * @default undefined
   */
  onChanged?: (
    mode: T | BasicColorMode,
    defaultHandler: (mode: T | BasicColorMode) => void
  ) => void
  /**
   * Custom storage ref
   *
   * When provided, `useStorage` will be skipped
   */
  storageRef?: Ref<T | BasicColorSchema>
  /**
   * Key to persist the data into localStorage/sessionStorage.
   *
   * Pass `null` to disable persistence
   *
   * @default 'vueuse-color-scheme'
   */
  storageKey?: string | null
  /**
   * Storage object, can be localStorage or sessionStorage
   *
   * @default localStorage
   */
  storage?: StorageLike
  /**
   * Emit `auto` mode from state
   *
   * When set to `true`, preferred mode won't be translated into `light` or `dark`.
   * This is useful when the fact that `auto` mode was selected needs to be known.
   *
   * @default undefined
   * @deprecated use `store.value` when `auto` mode needs to be known
   * @see https://vueuse.org/core/useColorMode/#advanced-usage
   */
  emitAuto?: boolean
  /**
   * Disable transition on switch
   *
   * @see https://paco.me/writing/disable-theme-transitions
   * @default true
   */
  disableTransition?: boolean
}
export type UseColorModeReturn<T extends string = BasicColorMode> = Ref<
  T | BasicColorSchema
> & {
  store: Ref<T | BasicColorSchema>
  system: ComputedRef<BasicColorMode>
  state: ComputedRef<T | BasicColorMode>
}
/**
 * Reactive color mode with auto data persistence.
 *
 * @see https://vueuse.org/useColorMode
 * @param options
 */
export declare function useColorMode<T extends string = BasicColorMode>(
  options?: UseColorModeOptions<T>
): UseColorModeReturn<T>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useColorMode/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useColorMode/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useColorMode/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useColorMode/>

useSessionStorage
=================




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 2.02 kB |
|  Last Changed  | 2 weeks ago |
|  Related  | [`useStorage`](../usestorage/index) |


Reactive [SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).


Usage
-----


Please refer to [`useStorage`](../usestorage/index)


Type Declarations
-----------------




```
export declare function useSessionStorage(
  key: string,
  initialValue: MaybeRefOrGetter<string>,
  options?: UseStorageOptions<string>
): RemovableRef<string>
export declare function useSessionStorage(
  key: string,
  initialValue: MaybeRefOrGetter<boolean>,
  options?: UseStorageOptions<boolean>
): RemovableRef<boolean>
export declare function useSessionStorage(
  key: string,
  initialValue: MaybeRefOrGetter<number>,
  options?: UseStorageOptions<number>
): RemovableRef<number>
export declare function useSessionStorage<T>(
  key: string,
  initialValue: MaybeRefOrGetter<T>,
  options?: UseStorageOptions<T>
): RemovableRef<T>
export declare function useSessionStorage<T = unknown>(
  key: string,
  initialValue: MaybeRefOrGetter<null>,
  options?: UseStorageOptions<T>
): RemovableRef<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useSessionStorage/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useSessionStorage/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useSessionStorage/>

useLocalStorage
===============




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 2.01 kB |
|  Last Changed  | 2 weeks ago |
|  Related  | [`useStorage`](../usestorage/index) |


Reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).


Usage
-----


Please refer to [`useStorage`](../usestorage/index)


Type Declarations
-----------------




```
export declare function useLocalStorage(
  key: string,
  initialValue: MaybeRefOrGetter<string>,
  options?: UseStorageOptions<string>
): RemovableRef<string>
export declare function useLocalStorage(
  key: string,
  initialValue: MaybeRefOrGetter<boolean>,
  options?: UseStorageOptions<boolean>
): RemovableRef<boolean>
export declare function useLocalStorage(
  key: string,
  initialValue: MaybeRefOrGetter<number>,
  options?: UseStorageOptions<number>
): RemovableRef<number>
export declare function useLocalStorage<T>(
  key: string,
  initialValue: MaybeRefOrGetter<T>,
  options?: UseStorageOptions<T>
): RemovableRef<T>
export declare function useLocalStorage<T = unknown>(
  key: string,
  initialValue: MaybeRefOrGetter<null>,
  options?: UseStorageOptions<T>
): RemovableRef<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useLocalStorage/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useLocalStorage/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useLocalStorage/>

useInfiniteScroll
=================




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 1.94 kB |
|  Last Changed  | last week |


Infinite scrolling of the element.


Usage
-----




```
<script setup lang="ts">
import { ref } from 'vue'
import { useInfiniteScroll } from '@vueuse/core'

const el = ref<HTMLElement>(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](../../guide/components). 
> 
> 




```
<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>
```


Type Declarations
-----------------




```
export interface UseInfiniteScrollOptions extends UseScrollOptions {
  /**
   * The minimum distance between the bottom of the element and the bottom of the viewport
   *
   * @default 0
   */
  distance?: number
  /**
   * The direction in which to listen the scroll.
   *
   * @default 'bottom'
   */
  direction?: "top" | "bottom" | "left" | "right"
  /**
   * The interval time between two load more (to avoid too many invokes).
   *
   * @default 100
   */
  interval?: number
}
/**
 * Reactive infinite scroll.
 *
 * @see https://vueuse.org/useInfiniteScroll
 */
export declare function useInfiniteScroll(
  element: MaybeRefOrGetter<
    HTMLElement | SVGElement | Window | Document | null | undefined
  >,
  onLoadMore: (
    state: UnwrapNestedRefs<ReturnType<typeof useScroll>>
  ) => Awaitable<void>,
  options?: UseInfiniteScrollOptions
): {
  isLoading: ComputedRef<boolean>
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useInfiniteScroll/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useInfiniteScroll/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useInfiniteScroll/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useInfiniteScroll/>

useVirtualList
==============




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 1.8 kB |
|  Last Changed  | 2 months ago |



**WARNING**Consider using [`vue-virtual-scroller`](https://github.com/Akryum/vue-virtual-scroller) instead, if you are looking for more features.



Create virtual lists with ease. Virtual lists (sometimes called [*virtual scrollers*](https://akryum.github.io/vue-virtual-scroller/)) allow you to render a large number of items performantly. They only render the minimum number of DOM nodes necessary to show the items within the `container` element by using the `wrapper` element to emulate the container element's full height.


Usage
-----


### Simple list




```
import { useVirtualList } from '@vueuse/core'

const { list, containerProps, wrapperProps } = useVirtualList(
  Array.from(Array(99999).keys()),
  {
    // Keep `itemHeight` in sync with the item's row.
    itemHeight: 22,
  },
)
```


### Config




| State | Type | Description |
| --- | --- | --- |
| itemHeight | `number` | ensure that the total height of the `wrapper` element is calculated correctly.\* |
| itemWidth | `number` | ensure that the total width of the `wrapper` element is calculated correctly.\* |
| overscan | `number` | number of pre-rendered DOM nodes. Prevents whitespace between items if you scroll very quickly. |


\* The `itemHeight` or `itemWidth` must be kept in sync with the height of each row rendered. If you are seeing extra whitespace or jitter when scrolling to the bottom of the list, ensure the `itemHeight` or `itemWidth` is the same height as the row.


### Reactive list




```
import { useVirtualList, useToggle } from '@vueuse/core'
import { computed } from 'vue'

const [isEven, toggle] = useToggle()
const allItems = Array.from(Array(99999).keys())
const filteredList = computed(() => allItems.filter(i => isEven.value ? i % 2 === 0 : i % 2 === 1))

const { list, containerProps, wrapperProps } = useVirtualList(
  filteredList,
  {
    itemHeight: 22,
  },
)
```




```
<template>
  <p>Showing {{ isEven ? 'even' : 'odd' }} items</p>
  <button @click="toggle">Toggle Even/Odd</button>
  <div v-bind="containerProps" style="height: 300px">
    <div v-bind="wrapperProps">
      <div v-for="item in list" :key="item.index" style="height: 22px">
        Row: {{ item.data }}
      </div>
    </div>
  </div>
</template>
```


### Horizontal list




```
import { useVirtualList } from '@vueuse/core'

const allItems = Array.from(Array(99999).keys())

const { list, containerProps, wrapperProps } = useVirtualList(
  allItems,
  {
    itemWidth: 200,
  },
)
```




```
<template>
  <div v-bind="containerProps" style="height: 300px">
    <div v-bind="wrapperProps">
      <div v-for="item in list" :key="item.index" style="width: 200px">
        Row: {{ item.data }}
      </div>
    </div>
  </div>
</template>
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseVirtualList :list="list" :options="options" height="300px">
  <template #="props">
    <!-- you can get current item of list here -->
    <div style="height: 22px">Row {{ props.data }}</div>
  </template>
</UseVirtualList>
```


To scroll to a specific element, the component exposes `scrollTo(index: number) => void`.


Type Declarations
-----------------



Show Type Declarations

```
type UseVirtualListItemSize = number | ((index: number) => number)
export interface UseHorizontalVirtualListOptions
  extends UseVirtualListOptionsBase {
  /**
   * item width, accept a pixel value or a function that returns the height
   *
   * @default 0
   */
  itemWidth: UseVirtualListItemSize
}
export interface UseVerticalVirtualListOptions
  extends UseVirtualListOptionsBase {
  /**
   * item height, accept a pixel value or a function that returns the height
   *
   * @default 0
   */
  itemHeight: UseVirtualListItemSize
}
export interface UseVirtualListOptionsBase {
  /**
   * the extra buffer items outside of the view area
   *
   * @default 5
   */
  overscan?: number
}
export type UseVirtualListOptions =
  | UseHorizontalVirtualListOptions
  | UseVerticalVirtualListOptions
export interface UseVirtualListItem<T> {
  data: T
  index: number
}
export interface UseVirtualListReturn<T> {
  list: Ref<UseVirtualListItem<T>[]>
  scrollTo: (index: number) => void
  containerProps: {
    ref: Ref<HTMLElement | null>
    onScroll: () => void
    style: StyleValue
  }
  wrapperProps: ComputedRef<{
    style:
      | {
          width: string
          height: string
          marginTop: string
        }
      | {
          width: string
          height: string
          marginLeft: string
          display: string
        }
  }>
}
/**
 * Please consider using [`vue-virtual-scroller`](https://github.com/Akryum/vue-virtual-scroller) if you are looking for more features.
 */
export declare function useVirtualList<T = any>(
  list: MaybeRef<T[]>,
  options: UseVirtualListOptions
): UseVirtualListReturn<T>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useVirtualList/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useVirtualList/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useVirtualList/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useVirtualList/>

useThrottledRefHistory
======================




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 1.73 kB |
|  Last Changed  | 9 months ago |
|  Related  | [`useDebouncedRefHistory`](../usedebouncedrefhistory/index)[`useRefHistory`](../userefhistory/index) |


Shorthand for [`useRefHistory`](../userefhistory/index) with throttled filter.


Usage
-----


This function takes the first snapshot right after the counter's value was changed and the second with a delay of 1000ms.




```
import { ref } from 'vue'
import { useThrottledRefHistory } from '@vueuse/core'

const counter = ref(0)
const { history, undo, redo } = useThrottledRefHistory(counter, { deep: true, throttle: 1000 })
```


Type Declarations
-----------------




```
export type UseThrottledRefHistoryOptions<Raw, Serialized = Raw> = Omit<
  UseRefHistoryOptions<Raw, Serialized>,
  "eventFilter"
> & {
  throttle?: MaybeRef<number>
  trailing?: boolean
}
export type UseThrottledRefHistoryReturn<
  Raw,
  Serialized = Raw
> = UseRefHistoryReturn<Raw, Serialized>
/**
 * Shorthand for [useRefHistory](https://vueuse.org/useRefHistory) with throttled filter.
 *
 * @see https://vueuse.org/useThrottledRefHistory
 * @param source
 * @param options
 */
export declare function useThrottledRefHistory<Raw, Serialized = Raw>(
  source: Ref<Raw>,
  options?: UseThrottledRefHistoryOptions<Raw, Serialized>
): UseThrottledRefHistoryReturn<Raw, Serialized>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useThrottledRefHistory/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useThrottledRefHistory/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useThrottledRefHistory/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useThrottledRefHistory/>

useDebouncedRefHistory
======================




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 1.7 kB |
|  Last Changed  | 2 weeks ago |
|  Related  | [`useRefHistory`](../userefhistory/index)[`useThrottledRefHistory`](../usethrottledrefhistory/index) |


Shorthand for [`useRefHistory`](../userefhistory/index) with debounced filter.


Usage
-----


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




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

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


Type Declarations
-----------------




```
/**
 * Shorthand for [useRefHistory](https://vueuse.org/useRefHistory) with debounce filter.
 *
 * @see https://vueuse.org/useDebouncedRefHistory
 * @param source
 * @param options
 */
export declare function useDebouncedRefHistory<Raw, Serialized = Raw>(
  source: Ref<Raw>,
  options?: Omit<UseRefHistoryOptions<Raw, Serialized>, "eventFilter"> & {
    debounce?: MaybeRefOrGetter<number>
  }
): UseRefHistoryReturn<Raw, Serialized>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDebouncedRefHistory/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDebouncedRefHistory/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDebouncedRefHistory/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDebouncedRefHistory/>

useStorageAsync
===============




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 1.63 kB |
|  Last Changed  | last week |
|  Related  | [`useStorage`](../usestorage/index) |


Reactive Storage in with async support.


Usage
-----


Please refer to [`useStorage`](../usestorage/index)


Type Declarations
-----------------



Show Type Declarations

```
export interface UseStorageAsyncOptions<T>
  extends Omit<UseStorageOptions<T>, "serializer"> {
  /**
   * Custom data serialization
   */
  serializer?: SerializerAsync<T>
}
export declare function useStorageAsync(
  key: string,
  initialValue: MaybeRefOrGetter<string>,
  storage?: StorageLikeAsync,
  options?: UseStorageAsyncOptions<string>
): RemovableRef<string>
export declare function useStorageAsync(
  key: string,
  initialValue: MaybeRefOrGetter<boolean>,
  storage?: StorageLikeAsync,
  options?: UseStorageAsyncOptions<boolean>
): RemovableRef<boolean>
export declare function useStorageAsync(
  key: string,
  initialValue: MaybeRefOrGetter<number>,
  storage?: StorageLikeAsync,
  options?: UseStorageAsyncOptions<number>
): RemovableRef<number>
export declare function useStorageAsync<T>(
  key: string,
  initialValue: MaybeRefOrGetter<T>,
  storage?: StorageLikeAsync,
  options?: UseStorageAsyncOptions<T>
): RemovableRef<T>
export declare function useStorageAsync<T = unknown>(
  key: string,
  initialValue: MaybeRefOrGetter<null>,
  storage?: StorageLikeAsync,
  options?: UseStorageAsyncOptions<T>
): RemovableRef<T>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useStorageAsync/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useStorageAsync/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useStorageAsync/>

useAnimate
==========




|  |  |
| --- | --- |
|  Category  | [Animation](../../functions#category=Animation) |
|  Export Size  | 1.56 kB |
|  Last Changed  | last week |


Reactive [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API).


Usage
-----


### Basic Usage


The [`useAnimate`](index) function will return the animate and its control function.




```
<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](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats) for more details.




```
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)
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseAnimateOptions
  extends KeyframeAnimationOptions,
    ConfigurableWindow {
  /**
   * Will automatically run play when `useAnimate` is used
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Whether to commits the end styling state of an animation to the element being animated
   *
   * @default false
   */
  commitStyles?: boolean
  /**
   * Whether to persists the animation
   *
   * @default false
   */
  persist?: boolean
  /**
   * Executed after animation initialization
   */
  onReady?: (animate: Animation) => void
  /**
   * Callback when error is caught.
   */
  onError?: (e: unknown) => void
}
export type UseAnimateKeyframes = MaybeRef<
  Keyframe[] | PropertyIndexedKeyframes | null
>
export interface UseAnimateReturn {
  isSupported: Ref<boolean>
  animate: ShallowRef<Animation | undefined>
  play: () => void
  pause: () => void
  reverse: () => void
  finish: () => void
  cancel: () => void
  pending: ComputedRef<boolean>
  playState: ComputedRef<AnimationPlayState>
  replaceState: ComputedRef<AnimationReplaceState>
  startTime: WritableComputedRef<number | null>
  currentTime: WritableComputedRef<CSSNumberish | null>
  timeline: WritableComputedRef<AnimationTimeline | null>
  playbackRate: WritableComputedRef<number>
}
/**
 * Reactive Web Animations API
 *
 * @see https://vueuse.org/useAnimate
 * @param target
 * @param keyframes
 * @param options
 */
export declare function useAnimate(
  target: MaybeComputedElementRef,
  keyframes: UseAnimateKeyframes,
  options?: number | UseAnimateOptions
): UseAnimateReturn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useAnimate/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useAnimate/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useAnimate/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useAnimate/>

useScroll
=========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 1.5 kB |
|  Last Changed  | 2 weeks ago |


Reactive scroll position and state.


Usage
-----




```
<script setup lang="ts">
import { useScroll } from '@vueuse/core'

const el = ref<HTMLElement | null>(null)
const { x, y, isScrolling, arrivedState, directions } = useScroll(el)
</script>

<template>
  <div ref="el"></div>
</template>
```


### With offsets




```
const { x, y, isScrolling, arrivedState, directions } = useScroll(el, {
  offset: { top: 30, bottom: 30, right: 30, left: 30 },
})
```


### Setting scroll position


Set the `x` and `y` values to make the element scroll to that position.




```
<script setup lang="ts">
import { useScroll } from '@vueuse/core'

const el = ref<HTMLElement | null>(null)
const { x, y } = useScroll(el)
</script>

<template>
  <div ref="el" />
  <button @click="x += 10">
    Scroll right 10px
  </button>
  <button @click="y += 10">
    Scroll down 10px
  </button>
</template>
```


### Smooth scrolling


Set `behavior: smooth` to enable smooth scrolling. The `behavior` option defaults to `auto`, which means no smooth scrolling. See the `behavior` option on [`window.scrollTo()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo) for more information.




```
import { useScroll } from '@vueuse/core'

const el = ref<HTMLElement | null>(null)
const { x, y } = useScroll(el, { behavior: 'smooth' })

// Or as a `ref`:
const smooth = ref(false)
const behavior = computed(() => smooth.value ? 'smooth' : 'auto')
const { x, y } = useScroll(el, { behavior })
```


Directive Usage
---------------



>  This function also provides a directive version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<script setup lang="ts">
import type { UseScrollReturn } from '@vueuse/core'
import { vScroll } from '@vueuse/components'

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

function onScroll(state: UseScrollReturn) {
  console.log(state) // {x, y, isScrolling, arrivedState, directions}
}
</script>

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

  <!-- with options -->
  <div v-scroll="[onScroll, { 'throttle' : 10 }]">
    <div v-for="item in data" :key="item">
      {{ item }}
    </div>
  </div>
</template>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseScrollOptions {
  /**
   * Throttle time for scroll event, it’s disabled by default.
   *
   * @default 0
   */
  throttle?: number
  /**
   * The check time when scrolling ends.
   * This configuration will be setting to (throttle + idle) when the `throttle` is configured.
   *
   * @default 200
   */
  idle?: number
  /**
   * Offset arrived states by x pixels
   *
   */
  offset?: {
    left?: number
    right?: number
    top?: number
    bottom?: number
  }
  /**
   * Trigger it when scrolling.
   *
   */
  onScroll?: (e: Event) => void
  /**
   * Trigger it when scrolling ends.
   *
   */
  onStop?: (e: Event) => void
  /**
   * Listener options for scroll event.
   *
   * @default {capture: false, passive: true}
   */
  eventListenerOptions?: boolean | AddEventListenerOptions
  /**
   * Optionally specify a scroll behavior of `auto` (default, not smooth scrolling) or
   * `smooth` (for smooth scrolling) which takes effect when changing the `x` or `y` refs.
   *
   * @default 'auto'
   */
  behavior?: MaybeRefOrGetter<ScrollBehavior>
}
/**
 * Reactive scroll.
 *
 * @see https://vueuse.org/useScroll
 * @param element
 * @param options
 */
export declare function useScroll(
  element: MaybeRefOrGetter<
    HTMLElement | SVGElement | Window | Document | null | undefined
  >,
  options?: UseScrollOptions
): {
  x: WritableComputedRef<number>
  y: WritableComputedRef<number>
  isScrolling: Ref<boolean>
  arrivedState: {
    left: boolean
    right: boolean
    top: boolean
    bottom: boolean
  }
  directions: {
    left: boolean
    right: boolean
    top: boolean
    bottom: boolean
  }
}
export type UseScrollReturn = ReturnType<typeof useScroll>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useScroll/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useScroll/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useScroll/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useScroll/>

useTimeAgo
==========




|  |  |
| --- | --- |
|  Category  | [Time](../../functions#category=Time) |
|  Export Size  | 1.63 kB |
|  Last Changed  | 2 weeks ago |


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


Usage
-----




```
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](../../guide/components). 
> 
> 




```
<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.




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

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


Type Declarations
-----------------



Show Type Declarations

```
export type UseTimeAgoFormatter<T = number> = (
  value: T,
  isPast: boolean
) => string
export type UseTimeAgoUnitNamesDefault =
  | "second"
  | "minute"
  | "hour"
  | "day"
  | "week"
  | "month"
  | "year"
export interface UseTimeAgoMessagesBuiltIn {
  justNow: string
  past: string | UseTimeAgoFormatter<string>
  future: string | UseTimeAgoFormatter<string>
  invalid: string
}
export type UseTimeAgoMessages<
  UnitNames extends string = UseTimeAgoUnitNamesDefault
> = UseTimeAgoMessagesBuiltIn &
  Record<UnitNames, string | UseTimeAgoFormatter<number>>
export interface FormatTimeAgoOptions<
  UnitNames extends string = UseTimeAgoUnitNamesDefault
> {
  /**
   * Maximum unit (of diff in milliseconds) to display the full date instead of relative
   *
   * @default undefined
   */
  max?: UnitNames | number
  /**
   * Formatter for full date
   */
  fullDateFormatter?: (date: Date) => string
  /**
   * Messages for formatting the string
   */
  messages?: UseTimeAgoMessages<UnitNames>
  /**
   * Minimum display time unit (default is minute)
   *
   * @default false
   */
  showSecond?: boolean
  /**
   * Rounding method to apply.
   *
   * @default 'round'
   */
  rounding?: "round" | "ceil" | "floor" | number
  /**
   * Custom units
   */
  units?: UseTimeAgoUnit<UseTimeAgoUnitNamesDefault>[]
}
export interface UseTimeAgoOptions<
  Controls extends boolean,
  UnitNames extends string = UseTimeAgoUnitNamesDefault
> extends FormatTimeAgoOptions<UnitNames> {
  /**
   * Expose more controls
   *
   * @default false
   */
  controls?: Controls
  /**
   * Intervals to update, set 0 to disable auto update
   *
   * @default 30_000
   */
  updateInterval?: number
}
export interface UseTimeAgoUnit<
  Unit extends string = UseTimeAgoUnitNamesDefault
> {
  max: number
  value: number
  name: Unit
}
export type UseTimeAgoReturn<Controls extends boolean = false> =
  Controls extends true
    ? {
        timeAgo: ComputedRef<string>
      } & Pausable
    : ComputedRef<string>
/**
 * Reactive time ago formatter.
 *
 * @see https://vueuse.org/useTimeAgo
 * @param options
 */
export declare function useTimeAgo<
  UnitNames extends string = UseTimeAgoUnitNamesDefault
>(
  time: MaybeRefOrGetter<Date | number | string>,
  options?: UseTimeAgoOptions<false, UnitNames>
): UseTimeAgoReturn<false>
export declare function useTimeAgo<
  UnitNames extends string = UseTimeAgoUnitNamesDefault
>(
  time: MaybeRefOrGetter<Date | number | string>,
  options: UseTimeAgoOptions<true, UnitNames>
): UseTimeAgoReturn<true>
export declare function formatTimeAgo<
  UnitNames extends string = UseTimeAgoUnitNamesDefault
>(
  from: Date,
  options?: FormatTimeAgoOptions<UnitNames>,
  now?: Date | number
): string
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTimeAgo/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTimeAgo/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTimeAgo/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTimeAgo/>

useUrlSearchParams
==================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 1.59 kB |
|  Last Changed  | 8 months ago |


Reactive [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)


Usage
-----




```
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`




```
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`




```
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`
```


Type Declarations
-----------------




```
export type UrlParams = Record<string, string[] | string>
export interface UseUrlSearchParamsOptions<T> extends ConfigurableWindow {
  /**
   * @default true
   */
  removeNullishValues?: boolean
  /**
   * @default false
   */
  removeFalsyValues?: boolean
  /**
   * @default {}
   */
  initialValue?: T
  /**
   * Write back to `window.history` automatically
   *
   * @default true
   */
  write?: boolean
}
/**
 * Reactive URLSearchParams
 *
 * @see https://vueuse.org/useUrlSearchParams
 * @param mode
 * @param options
 */
export declare function useUrlSearchParams<
  T extends Record<string, any> = UrlParams
>(
  mode?: "history" | "hash" | "hash-params",
  options?: UseUrlSearchParamsOptions<T>
): T
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useUrlSearchParams/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useUrlSearchParams/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useUrlSearchParams/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useUrlSearchParams/>

useScreenSafeArea
=================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 1.49 kB |
|  Last Changed  | last year |


Reactive `env(safe-area-inset-*)`


![image](https://webkit.org/wp-content/uploads/safe-areas-1.png)


Usage
-----


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




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


Then we could use [`useScreenSafeArea`](index) in the component as shown below:




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

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


For further details, you may refer to this documentation: [Designing Websites for iPhone X](https://webkit.org/blog/7929/designing-websites-for-iphone-x/)


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseScreenSafeArea top right bottom left>content</UseScreenSafeArea>
```


Type Declarations
-----------------




```
/**
 * Reactive `env(safe-area-inset-*)`
 *
 * @see https://vueuse.org/useScreenSafeArea
 */
export declare function useScreenSafeArea(): {
  top: Ref<string>
  right: Ref<string>
  bottom: Ref<string>
  left: Ref<string>
  update: () => void
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useScreenSafeArea/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useScreenSafeArea/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useScreenSafeArea/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useScreenSafeArea/>

useParallax
===========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 1.47 kB |
|  Last Changed  | 9 months ago |


Create parallax effect easily. It uses [`useDeviceOrientation`](../usedeviceorientation/index) and fallback to [`useMouse`](../usemouse/index) if orientation is not supported.


Usage
-----




```
<div ref='container'>
</div>
```




```
import { useParallax } from '@vueuse/core'

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

    return {
      container,
    }
  },
}
```


Type Declarations
-----------------




```
export interface UseParallaxOptions extends ConfigurableWindow {
  deviceOrientationTiltAdjust?: (i: number) => number
  deviceOrientationRollAdjust?: (i: number) => number
  mouseTiltAdjust?: (i: number) => number
  mouseRollAdjust?: (i: number) => number
}
export interface UseParallaxReturn {
  /**
   * Roll value. Scaled to `-0.5 ~ 0.5`
   */
  roll: ComputedRef<number>
  /**
   * Tilt value. Scaled to `-0.5 ~ 0.5`
   */
  tilt: ComputedRef<number>
  /**
   * Sensor source, can be `mouse` or `deviceOrientation`
   */
  source: ComputedRef<"deviceOrientation" | "mouse">
}
/**
 * Create parallax effect easily. It uses `useDeviceOrientation` and fallback to `useMouse`
 * if orientation is not supported.
 *
 * @param target
 * @param options
 */
export declare function useParallax(
  target: MaybeElementRef,
  options?: UseParallaxOptions
): UseParallaxReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useParallax/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useParallax/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useParallax/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useParallax/>

usePointerLock
==============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 1.36 kB |
|  Last Changed  | 3 months ago |


Reactive [pointer lock](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API).


Basic Usage
-----------




```
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](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
declare global {
  interface PointerLockOptions {
    unadjustedMovement?: boolean
  }
  interface Element {
    requestPointerLock(options?: PointerLockOptions): Promise<void> | void
  }
}
type MaybeHTMLElement = HTMLElement | undefined | null
export interface UsePointerLockOptions extends ConfigurableDocument {
  pointerLockOptions?: PointerLockOptions
}
/**
 * Reactive pointer lock.
 *
 * @see https://vueuse.org/usePointerLock
 * @param target
 * @param options
 */
export declare function usePointerLock(
  target?: MaybeElementRef<MaybeHTMLElement>,
  options?: UsePointerLockOptions
): {
  isSupported: ComputedRef<boolean>
  element: Ref<MaybeHTMLElement>
  triggerElement: Ref<MaybeHTMLElement>
  lock: (
    e: MaybeElementRef<MaybeHTMLElement> | Event,
    options?: PointerLockOptions
  ) => Promise<HTMLElement>
  unlock: () => Promise<boolean>
}
export type UsePointerLockReturn = ReturnType<typeof usePointerLock>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePointerLock/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePointerLock/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePointerLock/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePointerLock/>

useDraggable
============




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 1.35 kB |
|  Last Changed  | 2 weeks ago |


Make elements draggable.


Usage
-----




```
<script setup lang="ts">
import { ref } from 'vue'
import { useDraggable } from '@vueuse/core'

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

// `style` will be a helper computed for `left: ?px; top: ?px;`
const { x, y, style } = useDraggable(el, {
  initialValue: { x: 40, y: 40 },
})
</script>

<template>
  <div ref="el" :style="style" style="position: fixed">
    Drag me! I am at {{x}}, {{y}}
  </div>
</template>
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseDraggable :initialValue="{ x: 10, y: 10 }" v-slot="{ x, y }">
  Drag me! I am at {{x}}, {{y}}
</UseDraggable>
```


For component usage, additional props `storageKey` and `storageType` can be passed to the component and enable the persistence of the element position.




```
<UseDraggable storage-key="vueuse-draggable" storage-type="session">
  Refresh the page and I am still in the same position!
</UseDraggable>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseDraggableOptions {
  /**
   * Only start the dragging when click on the element directly
   *
   * @default false
   */
  exact?: MaybeRefOrGetter<boolean>
  /**
   * Prevent events defaults
   *
   * @default false
   */
  preventDefault?: MaybeRefOrGetter<boolean>
  /**
   * Prevent events propagation
   *
   * @default false
   */
  stopPropagation?: MaybeRefOrGetter<boolean>
  /**
   * Whether dispatch events in capturing phase
   *
   * @default true
   */
  capture?: boolean
  /**
   * Element to attach `pointermove` and `pointerup` events to.
   *
   * @default window
   */
  draggingElement?: MaybeRefOrGetter<
    HTMLElement | SVGElement | Window | Document | null | undefined
  >
  /**
   * Handle that triggers the drag event
   *
   * @default target
   */
  handle?: MaybeRefOrGetter<HTMLElement | SVGElement | null | undefined>
  /**
   * Pointer types that listen to.
   *
   * @default ['mouse', 'touch', 'pen']
   */
  pointerTypes?: PointerType[]
  /**
   * Initial position of the element.
   *
   * @default { x: 0, y: 0 }
   */
  initialValue?: MaybeRefOrGetter<Position>
  /**
   * Callback when the dragging starts. Return `false` to prevent dragging.
   */
  onStart?: (position: Position, event: PointerEvent) => void | false
  /**
   * Callback during dragging.
   */
  onMove?: (position: Position, event: PointerEvent) => void
  /**
   * Callback when dragging end.
   */
  onEnd?: (position: Position, event: PointerEvent) => void
  /**
   * Axis to drag on.
   *
   * @default 'both'
   */
  axis?: "x" | "y" | "both"
}
/**
 * Make elements draggable.
 *
 * @see https://vueuse.org/useDraggable
 * @param target
 * @param options
 */
export declare function useDraggable(
  target: MaybeRefOrGetter<HTMLElement | SVGElement | null | undefined>,
  options?: UseDraggableOptions
): {
  position: Ref<{
    x: number
    y: number
  }>
  isDragging: ComputedRef<boolean>
  style: ComputedRef<string>
  x: Ref<number>
  y: Ref<number>
}
export type UseDraggableReturn = ReturnType<typeof useDraggable>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDraggable/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDraggable/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDraggable/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDraggable/>

useWebSocket
============




|  |  |
| --- | --- |
|  Category  | [Network](../../functions#category=Network) |
|  Export Size  | 1.34 kB |
|  Last Changed  | 2 weeks ago |


Reactive [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket) client.


Usage
-----




```
import { useWebSocket } from '@vueuse/core'

const { status, data, send, open, close } = useWebSocket('ws://websocketurl')
```


See the [Type Declarations](#type-declarations) for more options.


### Immediate


Auto-connect (enabled by default).


This will call `open()` automatically for you and you don't need to call it by yourself.


If url is provided as a ref, this also controls whether a connection is re-established when its value is changed (or whether you need to call open() again for the change to take effect).


### Auto-close


Auto-close-connection (enabled by default).


This will call `close()` automatically when the `beforeunload` event is triggered or the associated effect scope is stopped.


### Auto-reconnection


Reconnect on errors automatically (disabled by default).




```
const { status, data, close } = useWebSocket('ws://websocketurl', {
  autoReconnect: true,
})
```


Or with more controls over its behavior:




```
const { status, data, close } = useWebSocket('ws://websocketurl', {
  autoReconnect: {
    retries: 3,
    delay: 1000,
    onFailed() {
      alert('Failed to connect WebSocket after 3 retries')
    },
  },
})
```


Explicitly calling `close()` won't trigger the auto reconnection.


### Heartbeat


It's common practice to send a small message (heartbeat) for every given time passed to keep the connection active. In this function we provide a convenient helper to do it:




```
const { status, data, close } = useWebSocket('ws://websocketurl', {
  heartbeat: true,
})
```


Or with more controls:




```
const { status, data, close } = useWebSocket('ws://websocketurl', {
  heartbeat: {
    message: 'ping',
    interval: 1000,
    pongTimeout: 1000,
  },
})
```


### Sub-protocols


List of one or more subprotocols to use, in this case soap and wamp.




```
import { useWebSocket } from '@vueuse/core'

const { status, data, send, open, close } = useWebSocket('ws://websocketurl', {
  protocols: ['soap'], // ['soap', 'wamp']
})
```


Type Declarations
-----------------



Show Type Declarations

```
export type WebSocketStatus = "OPEN" | "CONNECTING" | "CLOSED"
export interface UseWebSocketOptions {
  onConnected?: (ws: WebSocket) => void
  onDisconnected?: (ws: WebSocket, event: CloseEvent) => void
  onError?: (ws: WebSocket, event: Event) => void
  onMessage?: (ws: WebSocket, event: MessageEvent) => void
  /**
   * Send heartbeat for every x milliseconds passed
   *
   * @default false
   */
  heartbeat?:
    | boolean
    | {
        /**
         * Message for the heartbeat
         *
         * @default 'ping'
         */
        message?: string | ArrayBuffer | Blob
        /**
         * Interval, in milliseconds
         *
         * @default 1000
         */
        interval?: number
        /**
         * Heartbeat response timeout, in milliseconds
         *
         * @default 1000
         */
        pongTimeout?: number
      }
  /**
   * Enabled auto reconnect
   *
   * @default false
   */
  autoReconnect?:
    | boolean
    | {
        /**
         * Maximum retry times.
         *
         * Or you can pass a predicate function (which returns true if you want to retry).
         *
         * @default -1
         */
        retries?: number | (() => boolean)
        /**
         * Delay for reconnect, in milliseconds
         *
         * @default 1000
         */
        delay?: number
        /**
         * On maximum retry times reached.
         */
        onFailed?: Fn
      }
  /**
   * Automatically open a connection
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Automatically close a connection
   *
   * @default true
   */
  autoClose?: boolean
  /**
   * List of one or more sub-protocol strings
   *
   * @default []
   */
  protocols?: string[]
}
export interface UseWebSocketReturn<T> {
  /**
   * Reference to the latest data received via the websocket,
   * can be watched to respond to incoming messages
   */
  data: Ref<T | null>
  /**
   * The current websocket status, can be only one of:
   * 'OPEN', 'CONNECTING', 'CLOSED'
   */
  status: Ref<WebSocketStatus>
  /**
   * Closes the websocket connection gracefully.
   */
  close: WebSocket["close"]
  /**
   * Reopen the websocket connection.
   * If there the current one is active, will close it before opening a new one.
   */
  open: Fn
  /**
   * Sends data through the websocket connection.
   *
   * @param data
   * @param useBuffer when the socket is not yet open, store the data into the buffer and sent them one connected. Default to true.
   */
  send: (data: string | ArrayBuffer | Blob, useBuffer?: boolean) => boolean
  /**
   * Reference to the WebSocket instance.
   */
  ws: Ref<WebSocket | undefined>
}
/**
 * Reactive WebSocket client.
 *
 * @see https://vueuse.org/useWebSocket
 * @param url
 */
export declare function useWebSocket<Data = any>(
  url: MaybeRefOrGetter<string | URL | undefined>,
  options?: UseWebSocketOptions
): UseWebSocketReturn<Data>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebSocket/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebSocket/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useWebSocket/>

useGamepad
==========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 1.25 kB |
|  Last Changed  | 9 months ago |


Provides reactive bindings for the [Gamepad API](https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API).


Usage
-----



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




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

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

<template>
  <span>
    {{ gamepad.id }}
  <span>
</template>
```


### Gamepad Updates


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




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

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

pause()

// gamepads object will not update

resume()

// gamepads object will update on user input
```


### Gamepad Connect & Disconnect Events


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




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

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

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


### Vibration



> The Gamepad Haptics API is sparse, so check the [compatibility table](https://developer.mozilla.org/en-US/docs/Web/API/GamepadHapticActuator#browser_compatibility) before using.
> 
> 




```
import { computed } from 'vue'

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


### Mappings


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


#### Xbox360 Controller




```
<script setup>
import { mapGamepadToXbox360Controller } from '@vueuse/core'

const controller = mapGamepadToXbox360Controller(gamepad)
</script>

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


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


Type Declarations
-----------------



Show Type Declarations

```
export interface UseGamepadOptions
  extends ConfigurableWindow,
    ConfigurableNavigator {}
/**
 * Maps a standard standard gamepad to an Xbox 360 Controller.
 */
export declare function mapGamepadToXbox360Controller(
  gamepad: Ref<Gamepad | undefined>
): ComputedRef<{
  buttons: {
    a: GamepadButton
    b: GamepadButton
    x: GamepadButton
    y: GamepadButton
  }
  bumper: {
    left: GamepadButton
    right: GamepadButton
  }
  triggers: {
    left: GamepadButton
    right: GamepadButton
  }
  stick: {
    left: {
      horizontal: number
      vertical: number
      button: GamepadButton
    }
    right: {
      horizontal: number
      vertical: number
      button: GamepadButton
    }
  }
  dpad: {
    up: GamepadButton
    down: GamepadButton
    left: GamepadButton
    right: GamepadButton
  }
  back: GamepadButton
  start: GamepadButton
} | null>
export declare function useGamepad(options?: UseGamepadOptions): {
  isSupported: ComputedRef<boolean>
  onConnected: EventHookOn<number>
  onDisconnected: EventHookOn<number>
  gamepads: Ref<
    {
      readonly axes: readonly number[]
      readonly buttons: readonly {
        readonly pressed: boolean
        readonly touched: boolean
        readonly value: number
      }[]
      readonly connected: boolean
      readonly hapticActuators: readonly {
        readonly type: "vibration"
      }[]
      readonly id: string
      readonly index: number
      readonly mapping: GamepadMappingType
      readonly timestamp: number
    }[]
  >
  pause: Fn
  resume: Fn
  isActive: Readonly<Ref<boolean>>
}
export type UseGamepadReturn = ReturnType<typeof useGamepad>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useGamepad/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useGamepad/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useGamepad/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useGamepad/>

useElementBounding
==================




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 1.15 kB |
|  Last Changed  | 4 months ago |


Reactive [bounding box](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of an HTML element


Usage
-----




```
<template>
  <div ref="el" />
</template>

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

export default {
  setup() {
    const el = ref(null)
    const { x, y, top, right, bottom, left, width, height } = useElementBounding(el)

    return {
      el,
      /* ... */
    }
  }
}
</script>
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseElementBounding v-slot="{ width, height }">
  Width: {{ width }}
  Height: {{ height }}
</UseElementBounding>
```


Type Declarations
-----------------




```
export interface UseElementBoundingOptions {
  /**
   * Reset values to 0 on component unmounted
   *
   * @default true
   */
  reset?: boolean
  /**
   * Listen to window resize event
   *
   * @default true
   */
  windowResize?: boolean
  /**
   * Listen to window scroll event
   *
   * @default true
   */
  windowScroll?: boolean
  /**
   * Immediately call update on component mounted
   *
   * @default true
   */
  immediate?: boolean
}
/**
 * Reactive bounding box of an HTML element.
 *
 * @see https://vueuse.org/useElementBounding
 * @param target
 */
export declare function useElementBounding(
  target: MaybeComputedElementRef,
  options?: UseElementBoundingOptions
): {
  height: Ref<number>
  bottom: Ref<number>
  left: Ref<number>
  right: Ref<number>
  top: Ref<number>
  width: Ref<number>
  x: Ref<number>
  y: Ref<number>
  update: () => void
}
export type UseElementBoundingReturn = ReturnType<typeof useElementBounding>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementBounding/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementBounding/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementBounding/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useElementBounding/>

usePointer
==========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 1.14 kB |
|  Last Changed  | last week |


Reactive [pointer state](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events).


Basic Usage
-----------




```
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](../../guide/components). 
> 
> 


By default, the component will track the pointer on `window`




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


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




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


Type Declarations
-----------------



Show Type Declarations

```
export interface UsePointerState extends Position {
  pressure: number
  pointerId: number
  tiltX: number
  tiltY: number
  width: number
  height: number
  twist: number
  pointerType: PointerType | null
}
export interface UsePointerOptions extends ConfigurableWindow {
  /**
   * Pointer types that listen to.
   *
   * @default ['mouse', 'touch', 'pen']
   */
  pointerTypes?: PointerType[]
  /**
   * Initial values
   */
  initialValue?: MaybeRef<Partial<UsePointerState>>
  /**
   * @default window
   */
  target?: MaybeRef<EventTarget | null | undefined> | Document | Window
}
/**
 * Reactive pointer state.
 *
 * @see https://vueuse.org/usePointer
 * @param options
 */
export declare function usePointer(options?: UsePointerOptions): {
  isInside: Ref<boolean>
  pressure: Ref<number>
  pointerId: Ref<number>
  tiltX: Ref<number>
  tiltY: Ref<number>
  width: Ref<number>
  height: Ref<number>
  twist: Ref<number>
  pointerType: Ref<PointerType | null>
  x: Ref<number>
  y: Ref<number>
}
export type UsePointerReturn = ReturnType<typeof usePointer>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePointer/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePointer/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePointer/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePointer/>

useTransition
=============




|  |  |
| --- | --- |
|  Category  | [Animation](../../functions#category=Animation) |
|  Export Size  | 1.14 kB |
|  Last Changed  | last week |


Transition between values


Usage
-----


Define a numeric source value to follow, and when changed the output will transition to the new value. If the source changes while a transition is in progress, a new transition will begin from where the previous one was interrupted.




```
import { ref } from 'vue'
import { TransitionPresets, useTransition } from '@vueuse/core'

const source = ref(0)

const output = useTransition(source, {
  duration: 1000,
  transition: TransitionPresets.easeInOutCubic,
})
```


To synchronize transitions, use an array of numbers. As an example, here is how we could transition between colors.




```
const source = ref([0, 0, 0])

const output = useTransition(source)

const color = computed(() => {
  const [r, g, b] = output.value
  return `rgb(${r}, ${g}, ${b})`
})
```


Transition easing can be customized using cubic bezier curves. Transitions defined this way work the same as [CSS easing functions](https://developer.mozilla.org/en-US/docs/Web/CSS/easing-function#easing_functions).




```
useTransition(source, {
  transition: [0.75, 0, 0.25, 1],
})
```


The following transitions are available via the `TransitionPresets` constant.


* [`linear`](https://cubic-bezier.com/#0,0,1,1)
* [`easeInSine`](https://cubic-bezier.com/#.12,0,.39,0)
* [`easeOutSine`](https://cubic-bezier.com/#.61,1,.88,1)
* [`easeInOutSine`](https://cubic-bezier.com/#.37,0,.63,1)
* [`easeInQuad`](https://cubic-bezier.com/#.11,0,.5,0)
* [`easeOutQuad`](https://cubic-bezier.com/#.5,1,.89,1)
* [`easeInOutQuad`](https://cubic-bezier.com/#.45,0,.55,1)
* [`easeInCubic`](https://cubic-bezier.com/#.32,0,.67,0)
* [`easeOutCubic`](https://cubic-bezier.com/#.33,1,.68,1)
* [`easeInOutCubic`](https://cubic-bezier.com/#.65,0,.35,1)
* [`easeInQuart`](https://cubic-bezier.com/#.5,0,.75,0)
* [`easeOutQuart`](https://cubic-bezier.com/#.25,1,.5,1)
* [`easeInOutQuart`](https://cubic-bezier.com/#.76,0,.24,1)
* [`easeInQuint`](https://cubic-bezier.com/#.64,0,.78,0)
* [`easeOutQuint`](https://cubic-bezier.com/#.22,1,.36,1)
* [`easeInOutQuint`](https://cubic-bezier.com/#.83,0,.17,1)
* [`easeInExpo`](https://cubic-bezier.com/#.7,0,.84,0)
* [`easeOutExpo`](https://cubic-bezier.com/#.16,1,.3,1)
* [`easeInOutExpo`](https://cubic-bezier.com/#.87,0,.13,1)
* [`easeInCirc`](https://cubic-bezier.com/#.55,0,1,.45)
* [`easeOutCirc`](https://cubic-bezier.com/#0,.55,.45,1)
* [`easeInOutCirc`](https://cubic-bezier.com/#.85,0,.15,1)
* [`easeInBack`](https://cubic-bezier.com/#.36,0,.66,-.56)
* [`easeOutBack`](https://cubic-bezier.com/#.34,1.56,.64,1)
* [`easeInOutBack`](https://cubic-bezier.com/#.68,-.6,.32,1.6)


For more complex transitions, a custom function can be provided.




```
function easeOutElastic(n) {
  return n === 0
    ? 0
    : n === 1
      ? 1
      : (2 ** (-10 * n)) * Math.sin((n * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1
}

useTransition(source, {
  transition: easeOutElastic,
})
```


To control when a transition starts, set a `delay` value. To choreograph behavior around a transition, define `onStarted` or `onFinished` callbacks.




```
useTransition(source, {
  delay: 1000,
  onStarted() {
    // called after the transition starts
  },
  onFinished() {
    // called after the transition ends
  },
})
```


To temporarily stop transitioning, define a boolean `disabled` property. Be aware, this is not the same a `duration` of `0`. Disabled transitions track the source value ***synchronously***. They do not respect a `delay`, and do not fire `onStarted` or `onFinished` callbacks.


For more control, transitions can be executed manually by using `executeTransition`. This function returns a promise that resolves upon completion. Manual transitions can be cancelled by defining an `abort` function that returns a truthy value.




```
import { executeTransition } from '@vueuse/core'

await executeTransition(source, from, to, {
  duration: 1000,
})
```


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Cubic bezier points
 */
export type CubicBezierPoints = [number, number, number, number]
/**
 * Easing function
 */
export type EasingFunction = (n: number) => number
/**
 * Transition options
 */
export interface TransitionOptions {
  /**
   * Manually abort a transition
   */
  abort?: () => any
  /**
   * Transition duration in milliseconds
   */
  duration?: MaybeRef<number>
  /**
   * Easing function or cubic bezier points for calculating transition values
   */
  transition?: MaybeRef<EasingFunction | CubicBezierPoints>
}
export interface UseTransitionOptions extends TransitionOptions {
  /**
   * Milliseconds to wait before starting transition
   */
  delay?: MaybeRef<number>
  /**
   * Disables the transition
   */
  disabled?: MaybeRef<boolean>
  /**
   * Callback to execute after transition finishes
   */
  onFinished?: () => void
  /**
   * Callback to execute after transition starts
   */
  onStarted?: () => void
}
/**
 * Common transitions
 *
 * @see https://easings.net
 */
export declare const TransitionPresets: Record<
  | "easeInSine"
  | "easeOutSine"
  | "easeInOutSine"
  | "easeInQuad"
  | "easeOutQuad"
  | "easeInOutQuad"
  | "easeInCubic"
  | "easeOutCubic"
  | "easeInOutCubic"
  | "easeInQuart"
  | "easeOutQuart"
  | "easeInOutQuart"
  | "easeInQuint"
  | "easeOutQuint"
  | "easeInOutQuint"
  | "easeInExpo"
  | "easeOutExpo"
  | "easeInOutExpo"
  | "easeInCirc"
  | "easeOutCirc"
  | "easeInOutCirc"
  | "easeInBack"
  | "easeOutBack"
  | "easeInOutBack",
  CubicBezierPoints
> & {
  linear: EasingFunction
}
/**
 * Transition from one value to another.
 *
 * @param source
 * @param from
 * @param to
 * @param options
 */
export declare function executeTransition<T extends number | number[]>(
  source: Ref<T>,
  from: MaybeRefOrGetter<T>,
  to: MaybeRefOrGetter<T>,
  options?: TransitionOptions
): PromiseLike<void>
export declare function useTransition(
  source: MaybeRefOrGetter<number>,
  options?: UseTransitionOptions
): ComputedRef<number>
export declare function useTransition<T extends MaybeRefOrGetter<number>[]>(
  source: [...T],
  options?: UseTransitionOptions
): ComputedRef<{
  [K in keyof T]: number
}>
export declare function useTransition<T extends MaybeRefOrGetter<number[]>>(
  source: T,
  options?: UseTransitionOptions
): ComputedRef<number[]>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTransition/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTransition/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTransition/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTransition/>

useDevicesList
==============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 1.09 kB |
|  Last Changed  | 4 weeks ago |
|  Related  | [`useUserMedia`](../useusermedia/index) |


Reactive [enumerateDevices](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices) listing available input/output devices.


Usage
-----




```
import { useDevicesList } from '@vueuse/core'

const {
  devices,
  videoInputs: cameras,
  audioInputs: microphones,
  audioOutputs: speakers,
} = useDevicesList()
```


Component
=========




```
<UseDevicesList v-slot="{ videoInputs, audioInputs, audioOutputs }">
  Cameras: {{ videoInputs }}
  Microphones: {{ audioInputs }}
  Speakers: {{ audioOutputs }}
</UseDevicesList>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseDevicesListOptions extends ConfigurableNavigator {
  onUpdated?: (devices: MediaDeviceInfo[]) => void
  /**
   * Request for permissions immediately if it's not granted,
   * otherwise label and deviceIds could be empty
   *
   * @default false
   */
  requestPermissions?: boolean
  /**
   * Request for types of media permissions
   *
   * @default { audio: true, video: true }
   */
  constraints?: MediaStreamConstraints
}
export interface UseDevicesListReturn {
  /**
   * All devices
   */
  devices: Ref<MediaDeviceInfo[]>
  videoInputs: ComputedRef<MediaDeviceInfo[]>
  audioInputs: ComputedRef<MediaDeviceInfo[]>
  audioOutputs: ComputedRef<MediaDeviceInfo[]>
  permissionGranted: Ref<boolean>
  ensurePermissions: () => Promise<boolean>
  isSupported: Ref<boolean>
}
/**
 * Reactive `enumerateDevices` listing available input/output devices
 *
 * @see https://vueuse.org/useDevicesList
 * @param options
 */
export declare function useDevicesList(
  options?: UseDevicesListOptions
): UseDevicesListReturn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDevicesList/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDevicesList/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDevicesList/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDevicesList/>

useBrowserLocation
==================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 952 B |
|  Last Changed  | 2 months ago |


Reactive browser location



> NOTE: If you're using Vue Router, use [`useRoute`](https://router.vuejs.org/guide/advanced/composition-api.html) provided by Vue Router instead.
> 
> 


Usage
-----




```
import { useBrowserLocation } from '@vueuse/core'

const location = useBrowserLocation()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseBrowserLocation v-slot="{ location }">
  Browser Location: {{ location }}
</UseBrowserLocation>
```


Type Declarations
-----------------




```
export interface BrowserLocationState {
  readonly trigger: string
  readonly state?: any
  readonly length?: number
  readonly origin?: string
  hash?: string
  host?: string
  hostname?: string
  href?: string
  pathname?: string
  port?: string
  protocol?: string
  search?: string
}
/**
 * Reactive browser location.
 *
 * @see https://vueuse.org/useBrowserLocation
 * @param options
 */
export declare function useBrowserLocation({
  window,
}?: ConfigurableWindow): Ref<{
  readonly trigger: string
  readonly state?: any
  readonly length?: number | undefined
  readonly origin?: string | undefined
  hash?: string | undefined
  host?: string | undefined
  hostname?: string | undefined
  href?: string | undefined
  pathname?: string | undefined
  port?: string | undefined
  protocol?: string | undefined
  search?: string | undefined
}>
export type UseBrowserLocationReturn = ReturnType<typeof useBrowserLocation>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useBrowserLocation/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useBrowserLocation/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useBrowserLocation/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useBrowserLocation/>

useMouseInElement
=================




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 1.08 kB |
|  Last Changed  | 3 months ago |


Reactive mouse position related to an element


Usage
-----




```
<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](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export interface MouseInElementOptions extends UseMouseOptions {
  handleOutside?: boolean
}
/**
 * Reactive mouse position related to an element.
 *
 * @see https://vueuse.org/useMouseInElement
 * @param target
 * @param options
 */
export declare function useMouseInElement(
  target?: MaybeElementRef,
  options?: MouseInElementOptions
): {
  x: Ref<number>
  y: Ref<number>
  sourceType: Ref<UseMouseSourceType>
  elementX: Ref<number>
  elementY: Ref<number>
  elementPositionX: Ref<number>
  elementPositionY: Ref<number>
  elementHeight: Ref<number>
  elementWidth: Ref<number>
  isOutside: Ref<boolean>
  stop: () => void
}
export type UseMouseInElementReturn = ReturnType<typeof useMouseInElement>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMouseInElement/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMouseInElement/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMouseInElement/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMouseInElement/>

usePointerSwipe
===============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 1.04 kB |
|  Last Changed  | 2 weeks ago |


Reactive swipe detection based on [PointerEvents](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent).


Usage
-----




```
<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>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UsePointerSwipeOptions {
  /**
   * @default 50
   */
  threshold?: number
  /**
   * Callback on swipe start.
   */
  onSwipeStart?: (e: PointerEvent) => void
  /**
   * Callback on swipe move.
   */
  onSwipe?: (e: PointerEvent) => void
  /**
   * Callback on swipe end.
   */
  onSwipeEnd?: (e: PointerEvent, direction: UseSwipeDirection) => void
  /**
   * Pointer types to listen to.
   *
   * @default ['mouse', 'touch', 'pen']
   */
  pointerTypes?: PointerType[]
}
export interface UsePointerSwipeReturn {
  readonly isSwiping: Ref<boolean>
  direction: Readonly<Ref<UseSwipeDirection>>
  readonly posStart: Position
  readonly posEnd: Position
  distanceX: Readonly<Ref<number>>
  distanceY: Readonly<Ref<number>>
  stop: () => void
}
/**
 * Reactive swipe detection based on PointerEvents.
 *
 * @see https://vueuse.org/usePointerSwipe
 * @param target
 * @param options
 */
export declare function usePointerSwipe(
  target: MaybeRefOrGetter<HTMLElement | null | undefined>,
  options?: UsePointerSwipeOptions
): UsePointerSwipeReturn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePointerSwipe/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePointerSwipe/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePointerSwipe/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePointerSwipe/>

useFullscreen
=============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 1.01 kB |
|  Last Changed  | 2 days ago |


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


Usage
-----




```
import { useFullscreen } from '@vueuse/core'

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


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




```
const el = ref<HTMLElement | null>(null)

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




```
<video ref='el'>
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export interface UseFullscreenOptions extends ConfigurableDocument {
  /**
   * Automatically exit fullscreen when component is unmounted
   *
   * @default false
   */
  autoExit?: boolean
}
/**
 * Reactive Fullscreen API.
 *
 * @see https://vueuse.org/useFullscreen
 * @param target
 * @param options
 */
export declare function useFullscreen(
  target?: MaybeElementRef,
  options?: UseFullscreenOptions
): {
  isSupported: ComputedRef<boolean>
  isFullscreen: Ref<boolean>
  enter: () => Promise<void>
  exit: () => Promise<void>
  toggle: () => Promise<void>
}
export type UseFullscreenReturn = ReturnType<typeof useFullscreen>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useFullscreen/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useFullscreen/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useFullscreen/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useFullscreen/>

useClipboard
============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 1.02 kB |
|  Last Changed  | 2 weeks ago |


Reactive [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API). Provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard. Access to the contents of the clipboard is gated behind the [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API). Without user permission, reading or altering the clipboard contents is not permitted.


[Learn how to reactively save text to the clipboard with this FREE video lesson from Vue School!](https://vueschool.io/lessons/reactive-browser-wrappers-in-vueuse-useclipboard?friend=vueuse)Usage
-----




```
import { useClipboard } from '@vueuse/core'

const source = ref('Hello')
const { text, copy, copied, isSupported } = useClipboard({ source })
```




```
<div v-if="isSupported">
    <button @click='copy(source)'>
      <!-- by default, `copied` will be reset in 1.5s -->
      <span v-if='!copied'>Copy</span>
      <span v-else>Copied!</span>
    </button>
    <p>
      Current copied: <code>{{ text || 'none' }}</code>
    </p>
  </div>
  <p v-else>
    Your browser does not support Clipboard API
  </p>
```


Set `legacy: true` to keep the ability to copy if [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) is not available. It will handle copy with [execCommand](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) as fallback.


Type Declarations
-----------------



Show Type Declarations

```
export interface UseClipboardOptions<Source> extends ConfigurableNavigator {
  /**
   * Enabled reading for clipboard
   *
   * @default false
   */
  read?: boolean
  /**
   * Copy source
   */
  source?: Source
  /**
   * Milliseconds to reset state of `copied` ref
   *
   * @default 1500
   */
  copiedDuring?: number
  /**
   * Whether fallback to document.execCommand('copy') if clipboard is undefined.
   *
   * @default false
   */
  legacy?: boolean
}
export interface UseClipboardReturn<Optional> {
  isSupported: Ref<boolean>
  text: ComputedRef<string>
  copied: ComputedRef<boolean>
  copy: Optional extends true
    ? (text?: string) => Promise<void>
    : (text: string) => Promise<void>
}
/**
 * Reactive Clipboard API.
 *
 * @see https://vueuse.org/useClipboard
 * @param options
 */
export declare function useClipboard(
  options?: UseClipboardOptions<undefined>
): UseClipboardReturn<false>
export declare function useClipboard(
  options: UseClipboardOptions<MaybeRefOrGetter<string>>
): UseClipboardReturn<true>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useClipboard/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useClipboard/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useClipboard/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useClipboard/>

useSwipe
========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 983 B |
|  Last Changed  | 2 days ago |


Reactive swipe detection based on [`TouchEvents`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent).


Usage
-----




```
<template>
  <div ref="el">
    Swipe here
  </div>
</template>

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

    return { el, isSwiping, direction }
  } 
</script>
```


Type Declarations
-----------------



Show Type Declarations

```
export type UseSwipeDirection = "up" | "down" | "left" | "right" | "none"
export interface UseSwipeOptions extends ConfigurableWindow {
  /**
   * Register events as passive
   *
   * @default true
   */
  passive?: boolean
  /**
   * @default 50
   */
  threshold?: number
  /**
   * Callback on swipe start
   */
  onSwipeStart?: (e: TouchEvent) => void
  /**
   * Callback on swipe moves
   */
  onSwipe?: (e: TouchEvent) => void
  /**
   * Callback on swipe ends
   */
  onSwipeEnd?: (e: TouchEvent, direction: UseSwipeDirection) => void
}
export interface UseSwipeReturn {
  isPassiveEventSupported: boolean
  isSwiping: Ref<boolean>
  direction: ComputedRef<UseSwipeDirection>
  coordsStart: Readonly<Position>
  coordsEnd: Readonly<Position>
  lengthX: ComputedRef<number>
  lengthY: ComputedRef<number>
  stop: () => void
}
/**
 * Reactive swipe detection.
 *
 * @see https://vueuse.org/useSwipe
 * @param target
 * @param options
 */
export declare function useSwipe(
  target: MaybeRefOrGetter<EventTarget | null | undefined>,
  options?: UseSwipeOptions
): UseSwipeReturn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useSwipe/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useSwipe/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useSwipe/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useSwipe/>

useIdle
=======




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 977 B |
|  Last Changed  | last month |


Tracks whether the user is being inactive.


Usage
-----




```
import { useIdle } from '@vueuse/core'

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

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


Programatically resetting:




```
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](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export interface UseIdleOptions
  extends ConfigurableWindow,
    ConfigurableEventFilter {
  /**
   * Event names that listen to for detected user activity
   *
   * @default ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel']
   */
  events?: WindowEventName[]
  /**
   * Listen for document visibility change
   *
   * @default true
   */
  listenForVisibilityChange?: boolean
  /**
   * Initial state of the ref idle
   *
   * @default false
   */
  initialState?: boolean
}
export interface UseIdleReturn {
  idle: Ref<boolean>
  lastActive: Ref<number>
  reset: () => void
}
/**
 * Tracks whether the user is being inactive.
 *
 * @see https://vueuse.org/useIdle
 * @param timeout default to 1 minute
 * @param options IdleOptions
 */
export declare function useIdle(
  timeout?: number,
  options?: UseIdleOptions
): UseIdleReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useIdle/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useIdle/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useIdle/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useIdle/>

useMagicKeys
============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 1.02 kB |
|  Last Changed  | 2 weeks ago |


Reactive keys pressed state, with magical keys combination support.



 **This function uses [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)** It is **NOT** supported by [IE 11 or below](https://caniuse.com/proxy). 



Usage
-----




```
import { useMagicKeys } from '@vueuse/core'

const { shift, space, a /* keys you want to monitor */ } = useMagicKeys()

watch(space, (v) => {
  if (v)
    console.log('space has been pressed')
})

watchEffect(() => {
  if (shift.value && a.value)
    console.log('Shift + A have been pressed')
})
```


Check out [all the possible keycodes](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values).


### Combinations


You can magically use combinations (shortcuts/hotkeys) by connecting keys with `+` or `_`.




```
import { useMagicKeys } from '@vueuse/core'

const keys = useMagicKeys()
const shiftCtrlA = keys['Shift+Ctrl+A']

watch(shiftCtrlA, (v) => {
  if (v)
    console.log('Shift + Ctrl + A have been pressed')
})
```




```
import { useMagicKeys } from '@vueuse/core'

const { Ctrl_A_B, space, alt_s /* ... */ } = useMagicKeys()

watch(Ctrl_A_B, (v) => {
  if (v)
    console.log('Control+A+B have been pressed')
})
```


You can also use `whenever` function to make it shorter




```
import { useMagicKeys, whenever } from '@vueuse/core'

const keys = useMagicKeys()

whenever(keys.shift_space, () => {
  console.log('Shift+Space have been pressed')
})
```


### Current Pressed keys


A special property `current` is provided to representing all the keys been pressed currently.




```
import { useMagicKeys } from '@vueuse/core'

const { current } = useMagicKeys()

console.log(current) // Set { 'control', 'a' }

whenever(
  () => current.has('a') && !current.has('b'),
  () => console.log('A is pressed but not B'),
)
```


### Key Aliasing




```
import { useMagicKeys, whenever } from '@vueuse/core'

const { shift_cool } = useMagicKeys({
  aliasMap: {
    cool: 'space',
  },
})

whenever(shift_cool, () => console.log('Shift + Space have been pressed'))
```


By default, we have some [preconfigured alias for common practices](https://github.com/vueuse/vueuse/blob/main/packages/core/useMagicKeys/aliasMap.ts).


### Conditionally Disable


You might have some `<input />` elements in your apps, and you don't want to trigger the magic keys handling when users focused on those inputs. There is an example of using [`useActiveElement`](../useactiveelement/index) and [`logicAnd`](../../math/logicand/index) to do that.




```
import { useActiveElement, useMagicKeys, whenever } from '@vueuse/core'
import { logicAnd } from '@vueuse/math'

const activeElement = useActiveElement()
const notUsingInput = computed(() =>
  activeElement.value?.tagName !== 'INPUT'
  && activeElement.value?.tagName !== 'TEXTAREA',
)

const { tab } = useMagicKeys()

whenever(logicAnd(tab, notUsingInput), () => {
  console.log('Tab has been pressed outside of inputs!')
})
```


### Custom Event Handler




```
import { useMagicKeys, whenever } from '@vueuse/core'

const { ctrl_s } = useMagicKeys({
  passive: false,
  onEventFired(e) {
    if (e.ctrlKey && e.key === 's' && e.type === 'keydown')
      e.preventDefault()

  },
})

whenever(ctrl_s, () => console.log('Ctrl+S have been pressed'))
```



> ⚠️ This usage is NOT recommended, please use with caution.
> 
> 


### Reactive Mode


By default, the values of `useMagicKeys()` are `Ref<boolean>`. If you want to use the object in the template, you can set it to reactive mode.




```
const keys = useMagicKeys({ reactive: true })
```




```
<template>
  <div v-if="keys.shift">
    You are holding the Shift key!
  </div>
</template>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseMagicKeysOptions<Reactive extends Boolean> {
  /**
   * Returns a reactive object instead of an object of refs
   *
   * @default false
   */
  reactive?: Reactive
  /**
   * Target for listening events
   *
   * @default window
   */
  target?: MaybeRefOrGetter<EventTarget>
  /**
   * Alias map for keys, all the keys should be lowercase
   * { target: keycode }
   *
   * @example { ctrl: "control" }
   * @default <predefined-map>
   */
  aliasMap?: Record<string, string>
  /**
   * Register passive listener
   *
   * @default true
   */
  passive?: boolean
  /**
   * Custom event handler for keydown/keyup event.
   * Useful when you want to apply custom logic.
   *
   * When using `e.preventDefault()`, you will need to pass `passive: false` to useMagicKeys().
   */
  onEventFired?: (e: KeyboardEvent) => void | boolean
}
export interface MagicKeysInternal {
  /**
   * A Set of currently pressed keys,
   * Stores raw keyCodes.
   *
   * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
   */
  current: Set<string>
}
export type UseMagicKeysReturn<Reactive extends Boolean> = Readonly<
  Omit<
    Reactive extends true
      ? Record<string, boolean>
      : Record<string, ComputedRef<boolean>>,
    keyof MagicKeysInternal
  > &
    MagicKeysInternal
>
/**
 * Reactive keys pressed state, with magical keys combination support.
 *
 * @see https://vueuse.org/useMagicKeys
 */
export declare function useMagicKeys(
  options?: UseMagicKeysOptions<false>
): UseMagicKeysReturn<false>
export declare function useMagicKeys(
  options: UseMagicKeysOptions<true>
): UseMagicKeysReturn<true>
export { DefaultMagicKeysAliasMap } from "./aliasMap"
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMagicKeys/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMagicKeys/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMagicKeys/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMagicKeys/>

useWindowSize
=============




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 964 B |
|  Last Changed  | 2 weeks ago |


Reactive window size


Usage
-----




```
import { useWindowSize } from '@vueuse/core'

const { width, height } = useWindowSize()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseWindowSize v-slot="{ width, height }">
  Width: {{ width }}
  Height: {{ height }}
</UseWindowSize>
```


Type Declarations
-----------------




```
export interface UseWindowSizeOptions extends ConfigurableWindow {
  initialWidth?: number
  initialHeight?: number
  /**
   * Listen to window `orientationchange` event
   *
   * @default true
   */
  listenOrientation?: boolean
  /**
   * Whether the scrollbar should be included in the width and height
   * @default true
   */
  includeScrollbar?: boolean
}
/**
 * Reactive window size.
 *
 * @see https://vueuse.org/useWindowSize
 * @param options
 */
export declare function useWindowSize(options?: UseWindowSizeOptions): {
  width: Ref<number>
  height: Ref<number>
}
export type UseWindowSizeReturn = ReturnType<typeof useWindowSize>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useWindowSize/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useWindowSize/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useWindowSize/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useWindowSize/>

useElementSize
==============




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 950 B |
|  Last Changed  | 3 months ago |


Reactive size of an HTML element. [ResizeObserver MDN](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)


Usage
-----




```
<template>
  <div ref="el">
    Height: {{ height }}
    Width: {{ width }}
  </div>
</template>

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

export default {
  setup() {
    const el = ref(null)
    const { width, height } = useElementSize(el)

    return {
      el,
      width,
      height,
    }
  }
}
</script>
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseElementSize v-slot="{ width, height }">
  Width: {{ width }}
  Height: {{ height }}
</UseElementSize>
```


Directive Usage
---------------



>  This function also provides a directive version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<script setup lang="ts">
import { vElementSize } from '@vueuse/components'
function onResize({ width, height }: { width: number; height: number }) {
  console.log(width, height)
}
</script>

<template>
  <textarea v-element-size="onResize" />
  <!-- with options -->
  <textarea v-element-size="[onResize, {width:100,height:100}, {'box':'content-box'} ]" />
</template>
```


Type Declarations
-----------------




```
export interface ElementSize {
  width: number
  height: number
}
/**
 * Reactive size of an HTML element.
 *
 * @see https://vueuse.org/useElementSize
 * @param target
 * @param callback
 * @param options
 */
export declare function useElementSize(
  target: MaybeComputedElementRef,
  initialSize?: ElementSize,
  options?: UseResizeObserverOptions
): {
  width: Ref<number>
  height: Ref<number>
}
export type UseElementSizeReturn = ReturnType<typeof useElementSize>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementSize/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementSize/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementSize/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useElementSize/>

useScrollLock
=============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 919 B |
|  Last Changed  | 2 weeks ago |


Lock scrolling of the element.


Usage
-----




```
<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](../../guide/components). 
> 
> 




```
<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>
```


Type Declarations
-----------------




```
/**
 * Lock scrolling of the element.
 *
 * @see https://vueuse.org/useScrollLock
 * @param element
 */
export declare function useScrollLock(
  element: MaybeRefOrGetter<
    HTMLElement | SVGElement | Window | Document | null | undefined
  >,
  initialState?: boolean
): WritableComputedRef<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useScrollLock/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useScrollLock/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useScrollLock/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useScrollLock/>

useBreakpoints
==============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 915 B |
|  Last Changed  | 2 weeks ago |


Reactive viewport breakpoints.


Usage
-----




```
import { breakpointsTailwind, useBreakpoints } from '@vueuse/core'

const breakpoints = useBreakpoints(breakpointsTailwind)

const smAndLarger = breakpoints.greaterOrEqual('sm') // sm and larger
const largerThanSm = breakpoints.greater('sm') // only larger than sm
const lgAndSmaller = breakpoints.smallerOrEqual('lg') // lg and smaller
const smallerThanLg = breakpoints.smaller('lg') // only smaller than lg
```




```
import { useBreakpoints } from '@vueuse/core'

const breakpoints = useBreakpoints({
  tablet: 640,
  laptop: 1024,
  desktop: 1280,
})

const laptop = breakpoints.between('laptop', 'desktop')
```


Type Declarations
-----------------



Show Type Declarations

```
export * from "./breakpoints"
export type Breakpoints<K extends string = string> = Record<K, number | string>
/**
 * Reactively viewport breakpoints
 *
 * @see https://vueuse.org/useBreakpoints
 * @param options
 */
export declare function useBreakpoints<K extends string>(
  breakpoints: Breakpoints<K>,
  options?: ConfigurableWindow
): Record<K, Ref<boolean>> & {
  greater(k: K): Ref<boolean>
  greaterOrEqual: (k: K) => Ref<boolean>
  smaller(k: K): Ref<boolean>
  smallerOrEqual(k: K): Ref<boolean>
  between(a: K, b: K): Ref<boolean>
  isGreater(k: K): boolean
  isGreaterOrEqual(k: K): boolean
  isSmaller(k: K): boolean
  isSmallerOrEqual(k: K): boolean
  isInBetween(a: K, b: K): boolean
  current(): ComputedRef<string[]>
}
export type UseBreakpointsReturn<K extends string = string> = {
  greater: (k: K) => ComputedRef<boolean>
  greaterOrEqual: (k: K) => ComputedRef<boolean>
  smaller(k: K): ComputedRef<boolean>
  smallerOrEqual: (k: K) => ComputedRef<boolean>
  between(a: K, b: K): ComputedRef<boolean>
  isGreater(k: K): boolean
  isGreaterOrEqual(k: K): boolean
  isSmaller(k: K): boolean
  isSmallerOrEqual(k: K): boolean
  isInBetween(a: K, b: K): boolean
  current(): ComputedRef<string[]>
} & Record<K, ComputedRef<boolean>>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useBreakpoints/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useBreakpoints/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useBreakpoints/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useBreakpoints/>

useWebNotification
==================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 964 B |
|  Last Changed  | 4 weeks ago |


Reactive [Notification](https://developer.mozilla.org/en-US/docs/Web/API/notification)


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


Usage
-----




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

if (isSupported.value)
  show()
```


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




```
onClick((evt: Event) => {
  // Do something with the notification on:click event...
})

onShow((evt: Event) => {
  // Do something with the notification on:show event...
})

onError((evt: Event) => {
  // Do something with the notification on:error event...
})

onClose((evt: Event) => {
  // Do something with the notification on:close event...
})
```


Type Declarations
-----------------



Show Type Declarations

```
export interface WebNotificationOptions {
  /**
   * The title read-only property of the Notification interface indicates
   * the title of the notification
   *
   * @default ''
   */
  title?: string
  /**
   * The body string of the notification as specified in the constructor's
   * options parameter.
   *
   * @default ''
   */
  body?: string
  /**
   * The text direction of the notification as specified in the constructor's
   * options parameter.
   *
   * @default ''
   */
  dir?: "auto" | "ltr" | "rtl"
  /**
   * The language code of the notification as specified in the constructor's
   * options parameter.
   *
   * @default DOMString
   */
  lang?: string
  /**
   * The ID of the notification(if any) as specified in the constructor's options
   * parameter.
   *
   * @default ''
   */
  tag?: string
  /**
   * The URL of the image used as an icon of the notification as specified
   * in the constructor's options parameter.
   *
   * @default ''
   */
  icon?: string
  /**
   * Specifies whether the user should be notified after a new notification
   * replaces an old one.
   *
   * @default false
   */
  renotify?: boolean
  /**
   * A boolean value indicating that a notification should remain active until the
   * user clicks or dismisses it, rather than closing automatically.
   *
   * @default false
   */
  requireInteraction?: boolean
  /**
   * The silent read-only property of the Notification interface specifies
   * whether the notification should be silent, i.e., no sounds or vibrations
   * should be issued, regardless of the device settings.
   *
   * @default false
   */
  silent?: boolean
  /**
   * Specifies a vibration pattern for devices with vibration hardware to emit.
   * A vibration pattern, as specified in the Vibration API spec
   *
   * @see https://w3c.github.io/vibration/
   */
  vibrate?: number[]
}
export interface UseWebNotificationOptions
  extends WebNotificationOptions,
    ConfigurableWindow {}
/**
 * Reactive useWebNotification
 *
 * @see https://vueuse.org/useWebNotification
 * @see https://developer.mozilla.org/en-US/docs/Web/API/notification
 * @param title
 * @param defaultOptions of type WebNotificationOptions
 * @param methods of type WebNotificationMethods
 */
export declare function useWebNotification(
  defaultOptions?: UseWebNotificationOptions
): {
  isSupported: ComputedRef<boolean>
  notification: Ref<Notification | null>
  show: (
    overrides?: WebNotificationOptions
  ) => Promise<Notification | undefined>
  close: () => void
  onClick: EventHookOn<any>
  onShow: EventHookOn<any>
  onError: EventHookOn<any>
  onClose: EventHookOn<any>
}
export type UseWebNotificationReturn = ReturnType<typeof useWebNotification>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebNotification/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebNotification/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebNotification/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useWebNotification/>

useTextareaAutosize
===================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 857 B |
|  Last Changed  | 2 weeks ago |


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


Usage
-----




```
<script setup lang="ts">
const { textarea, input } = useTextareaAutosize()
</script>

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


Type Declarations
-----------------




```
export interface UseTextareaAutosizeOptions {
  /** Textarea element to autosize. */
  element?: MaybeRef<HTMLTextAreaElement | undefined>
  /** Textarea content. */
  input?: MaybeRef<string | undefined>
  /** Watch sources that should trigger a textarea resize. */
  watch?: WatchSource | Array<WatchSource>
  /** Function called when the textarea size changes. */
  onResize?: () => void
  /** Specify style target to apply the height based on textarea content. If not provided it will use textarea it self.  */
  styleTarget?: MaybeRef<HTMLElement>
}
export declare function useTextareaAutosize(
  options?: UseTextareaAutosizeOptions
): {
  textarea: Ref<HTMLTextAreaElement>
  input: Ref<string>
  triggerResize: () => void
}
export type UseTextareaAutosizeReturn = ReturnType<typeof useTextareaAutosize>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTextareaAutosize/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTextareaAutosize/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTextareaAutosize/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTextareaAutosize/>

useOnline
=========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 830 B |
|  Last Changed  | last year |


Reactive online state. A wrapper of [`useNetwork`](../usenetwork/index)


Usage
-----




```
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](../../guide/components). 
> 
> 




```
<UseOnline v-slot="{ isOnline }">
  Is Online: {{ isOnline }}
</UseOnline>
```


Type Declarations
-----------------




```
/**
 * Reactive online state.
 *
 * @see https://vueuse.org/useOnline
 * @param options
 */
export declare function useOnline(options?: ConfigurableWindow): Ref<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useOnline/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useOnline/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useOnline/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useOnline/>

useTextDirection
================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 821 B |
|  Last Changed  | 9 months ago |


Reactive [dir](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir) of the element's text.


Usage
-----




```
import { useTextDirection } from '@vueuse/core'

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


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




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

<!--rtl-->
<html dir="rtl"> ... </html>
```


Options
-------




```
import { useTextDirection } from '@vueuse/core'

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


Type Declarations
-----------------




```
export type UseTextDirectionValue = "ltr" | "rtl" | "auto"
export interface UseTextDirectionOptions extends ConfigurableDocument {
  /**
   * CSS Selector for the target element applying to
   *
   * @default 'html'
   */
  selector?: string
  /**
   * Observe `document.querySelector(selector)` changes using MutationObserve
   *
   * @default false
   */
  observe?: boolean
  /**
   * Initial value
   *
   * @default 'ltr'
   */
  initialValue?: UseTextDirectionValue
}
/**
 * Reactive dir of the element's text.
 *
 * @see https://vueuse.org/useTextDirection
 */
export declare function useTextDirection(
  options?: UseTextDirectionOptions
): WritableComputedRef<UseTextDirectionValue>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTextDirection/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTextDirection/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTextDirection/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTextDirection/>

useNetwork
==========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 814 B |
|  Last Changed  | 9 months ago |


Reactive [Network status](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API). 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.


Usage
-----




```
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()`




```
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](../../guide/components). 
> 
> 




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


Type Declarations
-----------------



Show Type Declarations

```
export type NetworkType =
  | "bluetooth"
  | "cellular"
  | "ethernet"
  | "none"
  | "wifi"
  | "wimax"
  | "other"
  | "unknown"
export type NetworkEffectiveType = "slow-2g" | "2g" | "3g" | "4g" | undefined
export interface NetworkState {
  isSupported: Ref<boolean>
  /**
   * If the user is currently connected.
   */
  isOnline: Ref<boolean>
  /**
   * The time since the user was last connected.
   */
  offlineAt: Ref<number | undefined>
  /**
   * At this time, if the user is offline and reconnects
   */
  onlineAt: Ref<number | undefined>
  /**
   * The download speed in Mbps.
   */
  downlink: Ref<number | undefined>
  /**
   * The max reachable download speed in Mbps.
   */
  downlinkMax: Ref<number | undefined>
  /**
   * The detected effective speed type.
   */
  effectiveType: Ref<NetworkEffectiveType | undefined>
  /**
   * The estimated effective round-trip time of the current connection.
   */
  rtt: Ref<number | undefined>
  /**
   * If the user activated data saver mode.
   */
  saveData: Ref<boolean | undefined>
  /**
   * The detected connection/network type.
   */
  type: Ref<NetworkType>
}
/**
 * Reactive Network status.
 *
 * @see https://vueuse.org/useNetwork
 * @param options
 */
export declare function useNetwork(
  options?: ConfigurableWindow
): Readonly<NetworkState>
export type UseNetworkReturn = ReturnType<typeof useNetwork>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useNetwork/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useNetwork/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useNetwork/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useNetwork/>

useFileSystemAccess
===================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 878 B |
|  Last Changed  | 2 weeks ago |


Create and read and write local files with [FileSystemAccessAPI](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API)


Usage
-----




```
import { useFileSystemAccess } from '@vueuse/core'

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


Type Declarations
-----------------



Show Type Declarations

```
/**
 * window.showOpenFilePicker parameters
 * @see https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker#parameters
 */
export interface FileSystemAccessShowOpenFileOptions {
  multiple?: boolean
  types?: Array<{
    description?: string
    accept: Record<string, string[]>
  }>
  excludeAcceptAllOption?: boolean
}
/**
 * window.showSaveFilePicker parameters
 * @see https://developer.mozilla.org/en-US/docs/Web/API/window/showSaveFilePicker#parameters
 */
export interface FileSystemAccessShowSaveFileOptions {
  suggestedName?: string
  types?: Array<{
    description?: string
    accept: Record<string, string[]>
  }>
  excludeAcceptAllOption?: boolean
}
/**
 * FileHandle
 * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle
 */
export interface FileSystemFileHandle {
  getFile: () => Promise<File>
  createWritable: () => FileSystemWritableFileStream
}
/**
 * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream
 */
interface FileSystemWritableFileStream extends WritableStream {
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/write
   */
  write: FileSystemWritableFileStreamWrite
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/seek
   */
  seek: (position: number) => Promise<void>
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/truncate
   */
  truncate: (size: number) => Promise<void>
}
/**
 * FileStream.write
 * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/write
 */
interface FileSystemWritableFileStreamWrite {
  (data: string | BufferSource | Blob): Promise<void>
  (options: {
    type: "write"
    position: number
    data: string | BufferSource | Blob
  }): Promise<void>
  (options: { type: "seek"; position: number }): Promise<void>
  (options: { type: "truncate"; size: number }): Promise<void>
}
/**
 * FileStream.write
 * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/write
 */
export type FileSystemAccessWindow = Window & {
  showSaveFilePicker: (
    options: FileSystemAccessShowSaveFileOptions
  ) => Promise<FileSystemFileHandle>
  showOpenFilePicker: (
    options: FileSystemAccessShowOpenFileOptions
  ) => Promise<FileSystemFileHandle[]>
}
export type UseFileSystemAccessCommonOptions = Pick<
  FileSystemAccessShowOpenFileOptions,
  "types" | "excludeAcceptAllOption"
>
export type UseFileSystemAccessShowSaveFileOptions = Pick<
  FileSystemAccessShowSaveFileOptions,
  "suggestedName"
>
export type UseFileSystemAccessOptions = ConfigurableWindow &
  UseFileSystemAccessCommonOptions & {
    /**
     * file data type
     */
    dataType?: MaybeRefOrGetter<"Text" | "ArrayBuffer" | "Blob">
  }
/**
 * Create and read and write local files.
 * @see https://vueuse.org/useFileSystemAccess
 * @param options
 */
export declare function useFileSystemAccess(
  options: UseFileSystemAccessOptions & {
    dataType: "Text"
  }
): UseFileSystemAccessReturn<string>
export declare function useFileSystemAccess(
  options: UseFileSystemAccessOptions & {
    dataType: "ArrayBuffer"
  }
): UseFileSystemAccessReturn<ArrayBuffer>
export declare function useFileSystemAccess(
  options: UseFileSystemAccessOptions & {
    dataType: "Blob"
  }
): UseFileSystemAccessReturn<Blob>
export declare function useFileSystemAccess(
  options: UseFileSystemAccessOptions
): UseFileSystemAccessReturn<string | ArrayBuffer | Blob>
export interface UseFileSystemAccessReturn<T = string> {
  isSupported: Ref<boolean>
  data: Ref<T | undefined>
  file: Ref<File | undefined>
  fileName: Ref<string>
  fileMIME: Ref<string>
  fileSize: Ref<number>
  fileLastModified: Ref<number>
  open: (_options?: UseFileSystemAccessCommonOptions) => Awaitable<void>
  create: (_options?: UseFileSystemAccessShowSaveFileOptions) => Awaitable<void>
  save: (_options?: UseFileSystemAccessShowSaveFileOptions) => Awaitable<void>
  saveAs: (_options?: UseFileSystemAccessShowSaveFileOptions) => Awaitable<void>
  updateData: () => Awaitable<void>
}
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useFileSystemAccess/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useFileSystemAccess/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useFileSystemAccess/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useFileSystemAccess/>

useCssVar
=========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 806 B |
|  Last Changed  | last week |


Manipulate CSS variables


Usage
-----




```
import { useCssVar } from '@vueuse/core'

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

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

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


Type Declarations
-----------------




```
export interface UseCssVarOptions extends ConfigurableWindow {
  initialValue?: string
  /**
   * Use MutationObserver to monitor variable changes
   * @default false
   */
  observe?: boolean
}
/**
 * Manipulate CSS variables.
 *
 * @see https://vueuse.org/useCssVar
 * @param prop
 * @param target
 * @param options
 */
export declare function useCssVar(
  prop: MaybeRefOrGetter<string>,
  target?: MaybeElementRef,
  options?: UseCssVarOptions
): Ref<string>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useCssVar/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useCssVar/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useCssVar/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useCssVar/>

useNow
======




|  |  |
| --- | --- |
|  Category  | [Animation](../../functions#category=Animation) |
|  Export Size  | 788 B |
|  Last Changed  | last year |


Reactive current Date instance.


Usage
-----




```
import { useNow } from '@vueuse/core'

const now = useNow()
```




```
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](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export interface UseNowOptions<Controls extends boolean> {
  /**
   * Expose more controls
   *
   * @default false
   */
  controls?: Controls
  /**
   * Update interval, or use requestAnimationFrame
   *
   * @default requestAnimationFrame
   */
  interval?: "requestAnimationFrame" | number
}
/**
 * Reactive current Date instance.
 *
 * @see https://vueuse.org/useNow
 * @param options
 */
export declare function useNow(options?: UseNowOptions<false>): Ref<Date>
export declare function useNow(options: UseNowOptions<true>): {
  now: Ref<Date>
} & Pausable
export type UseNowReturn = ReturnType<typeof useNow>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useNow/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useNow/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useNow/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useNow/>

useFocusWithin
==============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 769 B |
|  Last Changed  | 2 weeks 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.


Basic Usage
-----------




```
<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>
```


Type Declarations
-----------------




```
export interface UseFocusWithinReturn {
  /**
   * True if the element or any of its descendants are focused
   */
  focused: ComputedRef<boolean>
}
/**
 * Track if focus is contained within the target element
 *
 * @see https://vueuse.org/useFocusWithin
 * @param target The target element to track
 * @param options Focus within options
 */
export declare function useFocusWithin(
  target: MaybeElementRef,
  options?: ConfigurableWindow
): UseFocusWithinReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useFocusWithin/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useFocusWithin/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useFocusWithin/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useFocusWithin/>

usePermission
=============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 759 B |
|  Last Changed  | 10 months ago |
|  Related  | [`useUserMedia`](../useusermedia/index) |


Reactive [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API). The Permissions API provides the tools to allow developers to implement a better user experience as far as permissions are concerned.


Usage
-----




```
import { usePermission } from '@vueuse/core'

const microphoneAccess = usePermission('microphone')
```


Type Declarations
-----------------



Show Type Declarations

```
type DescriptorNamePolyfill =
  | "accelerometer"
  | "accessibility-events"
  | "ambient-light-sensor"
  | "background-sync"
  | "camera"
  | "clipboard-read"
  | "clipboard-write"
  | "gyroscope"
  | "magnetometer"
  | "microphone"
  | "notifications"
  | "payment-handler"
  | "persistent-storage"
  | "push"
  | "speaker"
export type GeneralPermissionDescriptor =
  | PermissionDescriptor
  | {
      name: DescriptorNamePolyfill
    }
export interface UsePermissionOptions<Controls extends boolean>
  extends ConfigurableNavigator {
  /**
   * Expose more controls
   *
   * @default false
   */
  controls?: Controls
}
export type UsePermissionReturn = Readonly<Ref<PermissionState | undefined>>
export interface UsePermissionReturnWithControls {
  state: UsePermissionReturn
  isSupported: Ref<boolean>
  query: () => Promise<PermissionStatus | undefined>
}
/**
 * Reactive Permissions API.
 *
 * @see https://vueuse.org/usePermission
 */
export declare function usePermission(
  permissionDesc:
    | GeneralPermissionDescriptor
    | GeneralPermissionDescriptor["name"],
  options?: UsePermissionOptions<false>
): UsePermissionReturn
export declare function usePermission(
  permissionDesc:
    | GeneralPermissionDescriptor
    | GeneralPermissionDescriptor["name"],
  options: UsePermissionOptions<true>
): UsePermissionReturnWithControls
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePermission/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePermission/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePermission/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePermission/>

useMouse
========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 790 B |
|  Last Changed  | 2 days ago |


Reactive mouse position


Basic Usage
-----------




```
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.




```
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.




```
import { type UseMouseEventExtractor, 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 })
```


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.




```
const { x, y } = useMouse({ touch: false })
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseMouse v-slot="{ x, y }">
  x: {{ x }}
  y: {{ y }}
</UseMouse>
```


Type Declarations
-----------------



Show Type Declarations

```
export type UseMouseCoordType = "page" | "client" | "screen" | "movement"
export type UseMouseSourceType = "mouse" | "touch" | null
export type UseMouseEventExtractor = (
  event: MouseEvent | Touch
) => [x: number, y: number] | null | undefined
export interface UseMouseOptions
  extends ConfigurableWindow,
    ConfigurableEventFilter {
  /**
   * Mouse position based by page, client, screen, or relative to previous position
   *
   * @default 'page'
   */
  type?: UseMouseCoordType | UseMouseEventExtractor
  /**
   * Listen events on `target` element
   *
   * @default 'Window'
   */
  target?: MaybeRefOrGetter<Window | EventTarget | null | undefined>
  /**
   * Listen to `touchmove` events
   *
   * @default true
   */
  touch?: boolean
  /**
   * Reset to initial value when `touchend` event fired
   *
   * @default false
   */
  resetOnTouchEnds?: boolean
  /**
   * Initial values
   */
  initialValue?: Position
}
/**
 * Reactive mouse position.
 *
 * @see https://vueuse.org/useMouse
 * @param options
 */
export declare function useMouse(options?: UseMouseOptions): {
  x: Ref<number>
  y: Ref<number>
  sourceType: Ref<UseMouseSourceType>
}
export type UseMouseReturn = ReturnType<typeof useMouse>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMouse/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMouse/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMouse/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMouse/>

useImage
========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 757 B |
|  Last Changed  | 2 weeks ago |


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


Usage
-----




```
<script setup>
import { useImage } from '@vueuse/core'

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

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


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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

    <template #error>
      Failed
    </template>
  </UseImage>
</template>
```


Type Declarations
-----------------




```
export interface UseImageOptions {
  /** Address of the resource */
  src: string
  /** Images to use in different situations, e.g., high-resolution displays, small monitors, etc. */
  srcset?: string
  /** Image sizes for different page layouts */
  sizes?: string
}
/**
 * Reactive load an image in the browser, you can wait the result to display it or show a fallback.
 *
 * @see https://vueuse.org/useImage
 * @param options Image attributes, as used in the <img> tag
 * @param asyncStateOptions
 */
export declare function useImage<Shallow extends true>(
  options: MaybeRefOrGetter<UseImageOptions>,
  asyncStateOptions?: UseAsyncStateOptions<Shallow>
): UseAsyncStateReturn<HTMLImageElement | undefined, [], true>
export type UseImageReturn = ReturnType<typeof useImage>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useImage/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useImage/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useImage/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useImage/>

useWebWorkerFn
==============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 749 B |
|  Last Changed  | 4 weeks ago |
|  Related  | [`useWebWorker`](../usewebworker/index) |


Run expensive functions without blocking the UI, using a simple syntax that makes use of Promise. A port of [alewin/useWorker](https://github.com/alewin/useWorker).


Usage
-----


### Basic example




```
import { useWebWorkerFn } from '@vueuse/core'

const { workerFn } = useWebWorkerFn(() => {
  // some heavy works to do in web worker
})
```


### With dependencies




```
import { useWebWorkerFn } from '@vueuse/core'

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


Web Worker
----------


Before you start using this function, we suggest you read the [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) documentation.


Credit
------


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


Type Declarations
-----------------




```
export type WebWorkerStatus =
  | "PENDING"
  | "SUCCESS"
  | "RUNNING"
  | "ERROR"
  | "TIMEOUT_EXPIRED"
export interface UseWebWorkerOptions extends ConfigurableWindow {
  /**
   * Number of milliseconds before killing the worker
   *
   * @default undefined
   */
  timeout?: number
  /**
   * An array that contains the external dependencies needed to run the worker
   */
  dependencies?: string[]
}
/**
 * Run expensive function without blocking the UI, using a simple syntax that makes use of Promise.
 *
 * @see https://vueuse.org/useWebWorkerFn
 * @param fn
 * @param options
 */
export declare function useWebWorkerFn<T extends (...fnArgs: any[]) => any>(
  fn: T,
  options?: UseWebWorkerOptions
): {
  workerFn: (...fnArgs: Parameters<T>) => Promise<ReturnType<T>>
  workerStatus: Ref<WebWorkerStatus>
  workerTerminate: (status?: WebWorkerStatus) => void
}
export type UseWebWorkerFnReturn = ReturnType<typeof useWebWorkerFn>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebWorkerFn/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebWorkerFn/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebWorkerFn/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useWebWorkerFn/>

useBase64
=========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 769 B |
|  Last Changed  | last week |


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


Usage
-----




```
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.


Type Declarations
-----------------



Show Type Declarations

```
export interface ToDataURLOptions {
  /**
   * MIME type
   */
  type?: string | undefined
  /**
   * Image quality of jpeg or webp
   */
  quality?: any
}
export interface UseBase64ObjectOptions<T> {
  serializer: (v: T) => string
}
export interface UseBase64Return {
  base64: Ref<string>
  promise: Ref<Promise<string>>
  execute: () => Promise<string>
}
export declare function useBase64(
  target: MaybeRefOrGetter<string>
): UseBase64Return
export declare function useBase64(
  target: MaybeRefOrGetter<Blob>
): UseBase64Return
export declare function useBase64(
  target: MaybeRefOrGetter<ArrayBuffer>
): UseBase64Return
export declare function useBase64(
  target: MaybeRefOrGetter<HTMLCanvasElement>,
  options?: ToDataURLOptions
): UseBase64Return
export declare function useBase64(
  target: MaybeRefOrGetter<HTMLImageElement>,
  options?: ToDataURLOptions
): UseBase64Return
export declare function useBase64<T extends Record<string, unknown>>(
  target: MaybeRefOrGetter<T>,
  options?: UseBase64ObjectOptions<T>
): UseBase64Return
export declare function useBase64<T extends Map<string, unknown>>(
  target: MaybeRefOrGetter<T>,
  options?: UseBase64ObjectOptions<T>
): UseBase64Return
export declare function useBase64<T extends Set<unknown>>(
  target: MaybeRefOrGetter<T>,
  options?: UseBase64ObjectOptions<T>
): UseBase64Return
export declare function useBase64<T>(
  target: MaybeRefOrGetter<T[]>,
  options?: UseBase64ObjectOptions<T[]>
): UseBase64Return
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useBase64/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useBase64/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useBase64/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useBase64/>

useBattery
==========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 743 B |
|  Last Changed  | 10 months ago |


Reactive [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/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.


Usage
-----




```
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](../../guide/components). 
> 
> 




```
<UseBattery v-slot="{ charging }">
  Is Charging: {{ charging }}
</UseBattery>
```


Type Declarations
-----------------




```
export interface BatteryManager extends EventTarget {
  charging: boolean
  chargingTime: number
  dischargingTime: number
  level: number
}
/**
 * Reactive Battery Status API.
 *
 * @see https://vueuse.org/useBattery
 * @param options
 */
export declare function useBattery({ navigator }?: ConfigurableNavigator): {
  isSupported: ComputedRef<boolean>
  charging: Ref<boolean>
  chargingTime: Ref<number>
  dischargingTime: Ref<number>
  level: Ref<number>
}
export type UseBatteryReturn = ReturnType<typeof useBattery>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useBattery/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useBattery/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useBattery/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useBattery/>

useWakeLock
===========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 727 B |
|  Last Changed  | 4 weeks ago |


Reactive [Screen Wake Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API). Provides a way to prevent devices from dimming or locking the screen when an application needs to keep running.


Usage
-----




```
import { useWakeLock } from '@vueuse/core'

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


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


Type Declarations
-----------------




```
type WakeLockType = "screen"
export interface WakeLockSentinel extends EventTarget {
  type: WakeLockType
  released: boolean
  release: () => Promise<void>
}
export type UseWakeLockOptions = ConfigurableNavigator & ConfigurableDocument
/**
 * Reactive Screen Wake Lock API.
 *
 * @see https://vueuse.org/useWakeLock
 * @param options
 */
export declare function useWakeLock(options?: UseWakeLockOptions): {
  isSupported: ComputedRef<boolean>
  isActive: Ref<boolean>
  request: (type: WakeLockType) => Promise<void>
  release: () => Promise<void>
}
export type UseWakeLockReturn = ReturnType<typeof useWakeLock>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useWakeLock/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useWakeLock/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useWakeLock/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useWakeLock/>

useActiveElement
================




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 712 B |
|  Last Changed  | 4 months ago |


Reactive `document.activeElement`


Usage
-----




```
import { useActiveElement } from '@vueuse/core'

const activeElement = useActiveElement()

watch(activeElement, (el) => {
  console.log('focus changed to', el)
})
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseActiveElement v-slot="{ element }">
  Active element is {{ element.dataset.id }}
</UseActiveElement>
```


Type Declarations
-----------------




```
export interface UseActiveElementOptions
  extends ConfigurableWindow,
    ConfigurableDocumentOrShadowRoot {}
/**
 * Reactive `document.activeElement`
 *
 * @see https://vueuse.org/useActiveElement
 * @param options
 */
export declare function useActiveElement<T extends HTMLElement>(
  options?: UseActiveElementOptions
): ComputedRefWithControl<T | null | undefined>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useActiveElement/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useActiveElement/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useActiveElement/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useActiveElement/>

onStartTyping
=============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 704 B |
|  Last Changed  | 3 weeks ago |


Fires when users start typing on non-editable elements.


Usage
-----




```
<input ref="input" type="text" placeholder="Start typing to focus" />
```




```
import { onStartTyping } from '@vueuse/core'

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

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

    return {
      input,
    }
  },
}
```


Type Declarations
-----------------




```
/**
 * Fires when users start typing on non-editable elements.
 *
 * @see https://vueuse.org/onStartTyping
 * @param callback
 * @param options
 */
export declare function onStartTyping(
  callback: (event: KeyboardEvent) => void,
  options?: ConfigurableDocument
): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/onStartTyping/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/onStartTyping/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/onStartTyping/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/onStartTyping/>

createReusableTemplate
======================




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 734 B |
|  Last Changed  | last week |


Define and reuse template inside the component scope.


Motivation
----------


It's common to have the need to reuse some part of the template. For example:




```
<template>
  <dialog v-if="showInDialog">
    <!-- something complex -->
  </dialog>
  <div v-else>
    <!-- something complex -->
  </div>
</template>
```


We'd like to reuse our code as much as possible. So normally we might need to extract those duplicated parts into a component. However, in a separated component you lose the ability to access the local bindings. Defining props and emits for them can be tedious sometime.


So this function is made to provide a way for defining and reusing templates inside the component scope.


Usage
-----


In the previous example, we could refactor it to:




```
<script setup>
import { createReusableTemplate } from '@vueuse/core'

const [DefineTemplate, ReuseTemplate] = createReusableTemplate()
</script>

<template>
  <DefineTemplate>
    <!-- something complex -->
  </DefineTemplate>

  <dialog v-if="showInDialog">
    <ReuseTemplate />
  </dialog>
  <div v-else>
    <ReuseTemplate />
  </div>
</template>
```


* `<DefineTemplate>` will register the template and renders nothing.
* `<ReuseTemplate>` will render the template provided by `<DefineTemplate>`.
* `<DefineTemplate>` must be used before `<ReuseTemplate>`.



> **Note**: It's recommended to extract as separate components whenever possible. Abusing this function might lead to bad practices for your codebase.
> 
> 


### Passing Data


You can also pass data to the template using slots:


* Use `v-slot="..."` to access the data on `<DefineTemplate>`
* Directly bind the data on `<ReuseTemplate>` to pass them to the template




```
<script setup>
import { createReusableTemplate } from '@vueuse/core'

const [DefineTemplate, ReuseTemplate] = createReusableTemplate()
</script>

<template>
  <DefineTemplate v-slot="{ data, msg, anything }">
    <div>{{ data }} passed from usage</div>
  </DefineTemplate>

  <ReuseTemplate :data="data" msg="The first usage" />
  <ReuseTemplate :data="anotherData" msg="The second usage" />
  <ReuseTemplate v-bind="{ data: something, msg: 'The third' }" />
</template>
```


### TypeScript Support


[`createReusableTemplate`](index) accepts a generic type to provide type support for the data passed to the template:




```
<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core'

// Comes with pair of `DefineTemplate` and `ReuseTemplate`
const [DefineFoo, ReuseFoo] = createReusableTemplate<{ msg: string }>()

// You can create multiple reusable templates
const [DefineBar, ReuseBar] = createReusableTemplate<{ items: string[] }>()
</script>

<template>
  <DefineFoo v-slot="{ msg }">
    <!-- `msg` is typed as `string` -->
    <div>Hello {{ msg.toUpperCase() }}</div>
  </DefineFoo>

  <ReuseFoo msg="World" />

  <!-- @ts-expect-error Type Error! -->
  <ReuseFoo :msg="1" />
</template>
```


Optionally, if you are not a fan of array destructuring, the following usages are also legal:




```
<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core'

const {
  define: DefineFoo,
  reuse: ReuseFoo,
} = createReusableTemplate<{ msg: string }>()
</script>

<template>
  <DefineFoo v-slot="{ msg }">
    <div>Hello {{ msg.toUpperCase() }}</div>
  </DefineFoo>

  <ReuseFoo msg="World" />
</template>
```




```
<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core'

const TemplateFoo = createReusableTemplate<{ msg: string }>()
</script>

<template>
  <TemplateFoo.define v-slot="{ msg }">
    <div>Hello {{ msg.toUpperCase() }}</div>
  </TemplateFoo.define>

  <TemplateFoo.reuse msg="World" />
</template>
```



**WARNING**Dot notation is not supported in Vue 2.



### Passing Slots


It's also possible to pass slots back from `<ReuseTemplate>`. You can access the slots on `<DefineTemplate>` from `$slots`:




```
<script setup>
import { createReusableTemplate } from '@vueuse/core'

const [DefineTemplate, ReuseTemplate] = createReusableTemplate()
</script>

<template>
  <DefineTemplate v-slot="{ $slots, otherProp }">
    <div some-layout>
      <!-- To render the slot -->
      <component :is="$slots.default" />
    </div>
  </DefineTemplate>

  <ReuseTemplate>
    <div>Some content</div>
  </ReuseTemplate>
  <ReuseTemplate>
    <div>Another content</div>
  </ReuseTemplate>
</template>
```



**WARNING**Passing slots does not work in Vue 2.



References
----------


This function is migrated from [vue-reuse-template](https://github.com/antfu/vue-reuse-template).


Existing Vue discussions/issues about reusing template:


* [Discussion on Reusing Templates](https://github.com/vuejs/core/discussions/6898)


Alternative Approaches:


* [Vue Macros - `namedTemplate`](https://vue-macros.sxzz.moe/features/named-template.html)
* [`unplugin-@vueuse/core`](https://github.com/liulinboyi/unplugin-@vueuse/core)


Type Declarations
-----------------



Show Type Declarations

```
export type DefineTemplateComponent<
  Bindings extends object,
  Slots extends Record<string, Slot | undefined>
> = DefineComponent<{}> & {
  new (): {
    $slots: {
      default(
        _: Bindings & {
          $slots: Slots
        }
      ): any
    }
  }
}
export type ReuseTemplateComponent<
  Bindings extends object,
  Slots extends Record<string, Slot | undefined>
> = DefineComponent<Bindings> & {
  new (): {
    $slots: Slots
  }
}
export type ReusableTemplatePair<
  Bindings extends object,
  Slots extends Record<string, Slot | undefined>
> = [
  DefineTemplateComponent<Bindings, Slots>,
  ReuseTemplateComponent<Bindings, Slots>
] & {
  define: DefineTemplateComponent<Bindings, Slots>
  reuse: ReuseTemplateComponent<Bindings, Slots>
}
/**
 * This function creates `define` and `reuse` components in pair,
 * It also allow to pass a generic to bind with type.
 *
 * @see https://vueuse.org/createReusableTemplate
 */
export declare function createReusableTemplate<
  Bindings extends object,
  Slots extends Record<string, Slot | undefined> = Record<
    string,
    Slot | undefined
  >
>(): ReusableTemplatePair<Bindings, Slots>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/createReusableTemplate/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/createReusableTemplate/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/createReusableTemplate/>

useSpeechSynthesis
==================




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 724 B |
|  Last Changed  | 2 weeks ago |


Reactive [SpeechSynthesis](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis).



> [Can I use?](https://caniuse.com/mdn-api_speechsynthesis)
> 
> 


Usage
-----




```
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](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis).




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


Type Declarations
-----------------



Show Type Declarations

```
export type UseSpeechSynthesisStatus = "init" | "play" | "pause" | "end"
export interface UseSpeechSynthesisOptions extends ConfigurableWindow {
  /**
   * Language for SpeechSynthesis
   *
   * @default 'en-US'
   */
  lang?: MaybeRefOrGetter<string>
  /**
   * Gets and sets the pitch at which the utterance will be spoken at.
   *
   * @default 1
   */
  pitch?: SpeechSynthesisUtterance["pitch"]
  /**
   * Gets and sets the speed at which the utterance will be spoken at.
   *
   * @default 1
   */
  rate?: SpeechSynthesisUtterance["rate"]
  /**
   * Gets and sets the voice that will be used to speak the utterance.
   */
  voice?: MaybeRef<SpeechSynthesisVoice>
  /**
   * Gets and sets the volume that the utterance will be spoken at.
   *
   * @default 1
   */
  volume?: SpeechSynthesisUtterance["volume"]
}
/**
 * Reactive SpeechSynthesis.
 *
 * @see https://vueuse.org/useSpeechSynthesis
 * @see https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis SpeechSynthesis
 * @param options
 */
export declare function useSpeechSynthesis(
  text: MaybeRefOrGetter<string>,
  options?: UseSpeechSynthesisOptions
): {
  isSupported: ComputedRef<boolean>
  isPlaying: Ref<boolean>
  status: Ref<UseSpeechSynthesisStatus>
  utterance: ComputedRef<SpeechSynthesisUtterance>
  error: Ref<SpeechSynthesisErrorEvent | undefined>
  stop: () => void
  toggle: (value?: boolean) => void
  speak: () => void
}
export type UseSpeechSynthesisReturn = ReturnType<typeof useSpeechSynthesis>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useSpeechSynthesis/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useSpeechSynthesis/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useSpeechSynthesis/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useSpeechSynthesis/>

useScreenOrientation
====================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 704 B |
|  Last Changed  | 4 weeks ago |


Reactive [Screen Orientation API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API). It provides web developers with information about the user's current screen orientation.


Usage
-----




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

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


To lock the orientation, you can pass an [OrientationLockType](https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/type) to the lockOrientation function:




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

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

lockOrientation('portrait-primary')
```


and then unlock again, with the following:




```
unlockOrientation()
```


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


[Screen Orientation API MDN](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API)


Type Declarations
-----------------




```
/**
 * Reactive screen orientation
 *
 * @see https://vueuse.org/useScreenOrientation
 */
export declare function useScreenOrientation(options?: ConfigurableWindow): {
  isSupported: ComputedRef<boolean>
  orientation: Ref<OrientationType | undefined>
  angle: Ref<number>
  lockOrientation: (type: OrientationLockType) => Promise<void>
  unlockOrientation: () => void
}
export type UseScreenOrientationReturn = ReturnType<typeof useScreenOrientation>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useScreenOrientation/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useScreenOrientation/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useScreenOrientation/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useScreenOrientation/>

useDeviceMotion
===============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 703 B |
|  Last Changed  | last year |


Reactive [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent). Provide web developers with information about the speed of changes for the device's position and orientation.


Usage
-----




```
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](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent#Properties).


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseDeviceMotion v-slot="{ acceleration }">
  Acceleration: {{ acceleration }}
</UseDeviceMotion>
```


Type Declarations
-----------------




```
export interface DeviceMotionOptions
  extends ConfigurableWindow,
    ConfigurableEventFilter {}
/**
 * Reactive DeviceMotionEvent.
 *
 * @see https://vueuse.org/useDeviceMotion
 * @param options
 */
export declare function useDeviceMotion(options?: DeviceMotionOptions): {
  acceleration: Ref<DeviceMotionEventAcceleration | null>
  accelerationIncludingGravity: Ref<DeviceMotionEventAcceleration | null>
  rotationRate: Ref<DeviceMotionEventRotationRate | null>
  interval: Ref<number>
}
export type UseDeviceMotionReturn = ReturnType<typeof useDeviceMotion>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDeviceMotion/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDeviceMotion/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDeviceMotion/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDeviceMotion/>

useSpeechRecognition
====================




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 694 B |
|  Last Changed  | 2 weeks ago |


Reactive [SpeechRecognition](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition).



> [Can I use?](https://caniuse.com/mdn-api_speechrecognitionevent)
> 
> 


Usage
-----




```
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](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition).




```
useSpeechRecognition({
  lang: 'en-US',
  interimResults: true,
  continuous: true,
})
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseSpeechRecognitionOptions extends ConfigurableWindow {
  /**
   * Controls whether continuous results are returned for each recognition, or only a single result.
   *
   * @default true
   */
  continuous?: boolean
  /**
   * Controls whether interim results should be returned (true) or not (false.) Interim results are results that are not yet final
   *
   * @default true
   */
  interimResults?: boolean
  /**
   * Language for SpeechRecognition
   *
   * @default 'en-US'
   */
  lang?: MaybeRefOrGetter<string>
}
/**
 * Reactive SpeechRecognition.
 *
 * @see https://vueuse.org/useSpeechRecognition
 * @see https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition SpeechRecognition
 * @param options
 */
export declare function useSpeechRecognition(
  options?: UseSpeechRecognitionOptions
): {
  isSupported: ComputedRef<boolean>
  isListening: Ref<boolean>
  isFinal: Ref<boolean>
  recognition: SpeechRecognition | undefined
  result: Ref<string>
  error: Ref<SpeechRecognitionErrorEvent | undefined>
  toggle: (value?: boolean) => void
  start: () => void
  stop: () => void
}
export type UseSpeechRecognitionReturn = ReturnType<typeof useSpeechRecognition>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useSpeechRecognition/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useSpeechRecognition/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useSpeechRecognition/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useSpeechRecognition/>

useMousePressed
===============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 679 B |
|  Last Changed  | 2 days ago |


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


Basic Usage
-----------




```
import { useMousePressed } from '@vueuse/core'

const { pressed } = useMousePressed()
```


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




```
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.




```
<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](../../guide/components). 
> 
> 




```
<UseMousePressed v-slot="{ pressed }">
  Is Pressed: {{ pressed }}
</UseMousePressed>
```


Type Declarations
-----------------




```
export interface MousePressedOptions extends ConfigurableWindow {
  /**
   * Listen to `touchstart` `touchend` events
   *
   * @default true
   */
  touch?: boolean
  /**
   * Listen to `dragstart` `drop` and `dragend` events
   *
   * @default true
   */
  drag?: boolean
  /**
   * Initial values
   *
   * @default false
   */
  initialValue?: boolean
  /**
   * Element target to be capture the click
   */
  target?: MaybeElementRef
}
/**
 * Reactive mouse position.
 *
 * @see https://vueuse.org/useMousePressed
 * @param options
 */
export declare function useMousePressed(options?: MousePressedOptions): {
  pressed: Ref<boolean>
  sourceType: Ref<UseMouseSourceType>
}
export type UseMousePressedReturn = ReturnType<typeof useMousePressed>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMousePressed/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMousePressed/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMousePressed/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMousePressed/>

useFileDialog
=============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 693 B |
|  Last Changed  | last month |


Open file dialog with ease.


Usage
-----




```
import { useFileDialog } from '@vueuse/core'

const { files, open, reset, onChange } = useFileDialog()

onChange((files) => {
  /** do something with files */
})
```




```
<template>
  <button type="button" @click="open">Choose file</button>
</template>
```


Type Declarations
-----------------




```
export interface UseFileDialogOptions extends ConfigurableDocument {
  /**
   * @default true
   */
  multiple?: boolean
  /**
   * @default '*'
   */
  accept?: string
  /**
   * Select the input source for the capture file.
   * @see [HTMLInputElement Capture](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/capture)
   */
  capture?: string
}
export interface UseFileDialogReturn {
  files: Ref<FileList | null>
  open: (localOptions?: Partial<UseFileDialogOptions>) => void
  reset: () => void
  onChange: EventHookOn<FileList | null>
}
/**
 * Open file dialog with ease.
 *
 * @see https://vueuse.org/useFileDialog
 * @param options
 */
export declare function useFileDialog(
  options?: UseFileDialogOptions
): UseFileDialogReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useFileDialog/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useFileDialog/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useFileDialog/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useFileDialog/>

useTextSelection
================




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 681 B |
|  Last Changed  | last year |


Reactively track user text selection based on [`Window.getSelection`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection).


Usage
-----




```
<template>
  <p>{{state.text}}</p>
</template>

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


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Reactively track user text selection based on [`Window.getSelection`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection).
 *
 * @see https://vueuse.org/useTextSelection
 */
export declare function useTextSelection(options?: ConfigurableWindow): {
  text: ComputedRef<string>
  rects: ComputedRef<DOMRect[]>
  ranges: ComputedRef<Range[]>
  selection: Ref<{
    readonly anchorNode: Node | null
    readonly anchorOffset: number
    readonly focusNode: Node | null
    readonly focusOffset: number
    readonly isCollapsed: boolean
    readonly rangeCount: number
    readonly type: string
    addRange: (range: Range) => void
    collapse: (node: Node | null, offset?: number | undefined) => void
    collapseToEnd: () => void
    collapseToStart: () => void
    containsNode: (
      node: Node,
      allowPartialContainment?: boolean | undefined
    ) => boolean
    deleteFromDocument: () => void
    empty: () => void
    extend: (node: Node, offset?: number | undefined) => void
    getRangeAt: (index: number) => Range
    modify: (
      alter?: string | undefined,
      direction?: string | undefined,
      granularity?: string | undefined
    ) => void
    removeAllRanges: () => void
    removeRange: (range: Range) => void
    selectAllChildren: (node: Node) => void
    setBaseAndExtent: (
      anchorNode: Node,
      anchorOffset: number,
      focusNode: Node,
      focusOffset: number
    ) => void
    setPosition: (node: Node | null, offset?: number | undefined) => void
    toString: () => string
  } | null>
}
export type UseTextSelectionReturn = ReturnType<typeof useTextSelection>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTextSelection/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTextSelection/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTextSelection/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTextSelection/>

useEventSource
==============




|  |  |
| --- | --- |
|  Category  | [Network](../../functions#category=Network) |
|  Export Size  | 679 B |
|  Last Changed  | last month |


An [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or [Server-Sent-Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format.


Usage
-----




```
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. |


Type Declarations
-----------------




```
export type UseEventSourceOptions = EventSourceInit
/**
 * Reactive wrapper for EventSource.
 *
 * @see https://vueuse.org/useEventSource
 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource EventSource
 * @param url
 * @param events
 * @param options
 */
export declare function useEventSource(
  url: string,
  events?: Array<string>,
  options?: UseEventSourceOptions
): {
  eventSource: Ref<EventSource | null>
  event: Ref<string | null>
  data: Ref<string | null>
  status: Ref<"OPEN" | "CONNECTING" | "CLOSED">
  error: Ref<Event | null>
  close: () => void
}
export type UseEventSourceReturn = ReturnType<typeof useEventSource>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useEventSource/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useEventSource/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useEventSource/>

useVibrate
==========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 671 B |
|  Last Changed  | 2 weeks ago |


Reactive [Vibration API](https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API)


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


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


Usage
-----


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


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




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

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

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

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


Type Declarations
-----------------



Show Type Declarations

```
export interface UseVibrateOptions extends ConfigurableNavigator {
  /**
   *
   * Vibration Pattern
   *
   * An array of values describes alternating periods in which the
   * device is vibrating and not vibrating. Each value in the array
   * is converted to an integer, then interpreted alternately as
   * the number of milliseconds the device should vibrate and the
   * number of milliseconds it should not be vibrating
   *
   * @default []
   *
   */
  pattern?: MaybeRefOrGetter<number[] | number>
  /**
   * Interval to run a persistent vibration, in ms
   *
   * Pass `0` to disable
   *
   * @default 0
   *
   */
  interval?: number
}
/**
 * Reactive vibrate
 *
 * @see https://vueuse.org/useVibrate
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API
 * @param options
 */
export declare function useVibrate(options?: UseVibrateOptions): {
  isSupported: ComputedRef<boolean>
  pattern: MaybeRefOrGetter<number | number[]>
  intervalControls: Pausable | undefined
  vibrate: (pattern?: number | number[]) => void
  stop: () => void
}
export type UseVibrateReturn = ReturnType<typeof useVibrate>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useVibrate/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useVibrate/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useVibrate/>

useScriptTag
============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 676 B |
|  Last Changed  | 2 weeks ago |


Script tag injecting.


Usage
-----




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

useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  // on script tag loaded.
  (el: HTMLScriptElement) => {
    // do something
  },
)
```


The script will be automatically loaded on the component mounted and removed when the component on unmounting.


Configurations
--------------


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




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

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

// manual controls
await load()
await unload()
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseScriptTagOptions extends ConfigurableDocument {
  /**
   * Load the script immediately
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Add `async` attribute to the script tag
   *
   * @default true
   */
  async?: boolean
  /**
   * Script type
   *
   * @default 'text/javascript'
   */
  type?: string
  /**
   * Manual controls the timing of loading and unloading
   *
   * @default false
   */
  manual?: boolean
  crossOrigin?: "anonymous" | "use-credentials"
  referrerPolicy?:
    | "no-referrer"
    | "no-referrer-when-downgrade"
    | "origin"
    | "origin-when-cross-origin"
    | "same-origin"
    | "strict-origin"
    | "strict-origin-when-cross-origin"
    | "unsafe-url"
  noModule?: boolean
  defer?: boolean
  /**
   * Add custom attribute to the script tag
   *
   */
  attrs?: Record<string, string>
}
/**
 * Async script tag loading.
 *
 * @see https://vueuse.org/useScriptTag
 * @param src
 * @param onLoaded
 * @param options
 */
export declare function useScriptTag(
  src: MaybeRefOrGetter<string>,
  onLoaded?: (el: HTMLScriptElement) => void,
  options?: UseScriptTagOptions
): {
  scriptTag: Ref<HTMLScriptElement | null>
  load: (waitForScriptLoad?: boolean) => Promise<HTMLScriptElement | boolean>
  unload: () => void
}
export type UseScriptTagReturn = ReturnType<typeof useScriptTag>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useScriptTag/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useScriptTag/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useScriptTag/>

onLongPress
===========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 675 B |
|  Last Changed  | 8 months ago |


Listen for a long press on an element.


Function provides modifiers in options


* stop
* once
* prevent
* capture
* self


Usage
-----




```
<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](../../guide/components). 
> 
> 




```
<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](../../guide/components). 
> 
> 




```
<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>
```


Type Declarations
-----------------




```
export interface OnLongPressOptions {
  /**
   * Time in ms till `longpress` gets called
   *
   * @default 500
   */
  delay?: number
  modifiers?: OnLongPressModifiers
}
export interface OnLongPressModifiers {
  stop?: boolean
  once?: boolean
  prevent?: boolean
  capture?: boolean
  self?: boolean
}
export declare function onLongPress(
  target: MaybeElementRef,
  handler: (evt: PointerEvent) => void,
  options?: OnLongPressOptions
): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/onLongPress/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/onLongPress/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/onLongPress/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/onLongPress/>

useDeviceOrientation
====================




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 672 B |
|  Last Changed  | 10 months ago |


Reactive [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent). Provide web developers with information from the physical orientation of the device running the web page.


Usage
-----




```
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](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent#Properties).


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
/**
 * Reactive DeviceOrientationEvent.
 *
 * @see https://vueuse.org/useDeviceOrientation
 * @param options
 */
export declare function useDeviceOrientation(options?: ConfigurableWindow): {
  isSupported: ComputedRef<boolean>
  isAbsolute: Ref<boolean>
  alpha: Ref<number | null>
  beta: Ref<number | null>
  gamma: Ref<number | null>
}
export type UseDeviceOrientationReturn = ReturnType<typeof useDeviceOrientation>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDeviceOrientation/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDeviceOrientation/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDeviceOrientation/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDeviceOrientation/>

useResizeObserver
=================




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 672 B |
|  Last Changed  | 4 weeks ago |


Reports changes to the dimensions of an Element's content or the border-box


Usage
-----




```
<template>
  <div ref="el">
    {{text}}
  </div>
</template>

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

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

    useResizeObserver(el, (entries) => {
      const entry = entries[0]
      const { width, height } = entry.contentRect
      text.value = `width: ${width}, height: ${height}`
    })

    return {
      el,
      text,
    }
  }
}
</script>
```


[ResizeObserver MDN](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)


Type Declarations
-----------------



Show Type Declarations

```
export interface ResizeObserverSize {
  readonly inlineSize: number
  readonly blockSize: number
}
export interface ResizeObserverEntry {
  readonly target: Element
  readonly contentRect: DOMRectReadOnly
  readonly borderBoxSize?: ReadonlyArray<ResizeObserverSize>
  readonly contentBoxSize?: ReadonlyArray<ResizeObserverSize>
  readonly devicePixelContentBoxSize?: ReadonlyArray<ResizeObserverSize>
}
export type ResizeObserverCallback = (
  entries: ReadonlyArray<ResizeObserverEntry>,
  observer: ResizeObserver
) => void
export interface UseResizeObserverOptions extends ConfigurableWindow {
  /**
   * Sets which box model the observer will observe changes to. Possible values
   * are `content-box` (the default), `border-box` and `device-pixel-content-box`.
   *
   * @default 'content-box'
   */
  box?: ResizeObserverBoxOptions
}
declare class ResizeObserver {
  constructor(callback: ResizeObserverCallback)
  disconnect(): void
  observe(target: Element, options?: UseResizeObserverOptions): void
  unobserve(target: Element): void
}
/**
 * Reports changes to the dimensions of an Element's content or the border-box
 *
 * @see https://vueuse.org/useResizeObserver
 * @param target
 * @param callback
 * @param options
 */
export declare function useResizeObserver(
  target: MaybeComputedElementRef | MaybeComputedElementRef[],
  callback: ResizeObserverCallback,
  options?: UseResizeObserverOptions
): {
  isSupported: ComputedRef<boolean>
  stop: () => void
}
export type UseResizeObserverReturn = ReturnType<typeof useResizeObserver>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useResizeObserver/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useResizeObserver/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useResizeObserver/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useResizeObserver/>

onKeyStroke
===========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 651 B |
|  Last Changed  | 2 weeks ago |


Listen for keyboard key being stroked.


Usage
-----




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

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


See [this table](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) for all key codes.


### Listen To Multiple Keys




```
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




```
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**.




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

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


Reference: [KeyboardEvent.repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat)


Directive Usage
---------------



>  This function also provides a directive version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<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




```
onKeyStroke('Shift', (e) => {
  console.log('Shift key up')
}, { eventName: 'keyup' })
```


Or




```
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'})`


Type Declarations
-----------------



Show Type Declarations

```
export type KeyPredicate = (event: KeyboardEvent) => boolean
export type KeyFilter = true | string | string[] | KeyPredicate
export type KeyStrokeEventName = "keydown" | "keypress" | "keyup"
export interface OnKeyStrokeOptions {
  eventName?: KeyStrokeEventName
  target?: MaybeRefOrGetter<EventTarget | null | undefined>
  passive?: boolean
  /**
   * Set to `true` to ignore repeated events when the key is being held down.
   *
   * @default false
   */
  dedupe?: MaybeRefOrGetter<boolean>
}
export declare function onKeyStroke(
  key: KeyFilter,
  handler: (event: KeyboardEvent) => void,
  options?: OnKeyStrokeOptions
): () => void
export declare function onKeyStroke(
  handler: (event: KeyboardEvent) => void,
  options?: OnKeyStrokeOptions
): () => void
/**
 * Listen for keyboard keys being stroked.
 *
 * @see https://vueuse.org/onKeyStroke
 */
export declare function onKeyStroke(
  key: KeyFilter,
  handler: (event: KeyboardEvent) => void,
  options?: OnKeyStrokeOptions
): () => void
export declare function onKeyStroke(
  handler: (event: KeyboardEvent) => void,
  options?: OnKeyStrokeOptions
): () => void
/**
 * Listen to the keydown event of the given key.
 *
 * @see https://vueuse.org/onKeyStroke
 * @param key
 * @param handler
 * @param options
 */
export declare function onKeyDown(
  key: KeyFilter,
  handler: (event: KeyboardEvent) => void,
  options?: Omit<OnKeyStrokeOptions, "eventName">
): () => void
/**
 * Listen to the keypress event of the given key.
 *
 * @see https://vueuse.org/onKeyStroke
 * @param key
 * @param handler
 * @param options
 */
export declare function onKeyPressed(
  key: KeyFilter,
  handler: (event: KeyboardEvent) => void,
  options?: Omit<OnKeyStrokeOptions, "eventName">
): () => void
/**
 * Listen to the keyup event of the given key.
 *
 * @see https://vueuse.org/onKeyStroke
 * @param key
 * @param handler
 * @param options
 */
export declare function onKeyUp(
  key: KeyFilter,
  handler: (event: KeyboardEvent) => void,
  options?: Omit<OnKeyStrokeOptions, "eventName">
): () => void
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/onKeyStroke/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/onKeyStroke/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/onKeyStroke/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/onKeyStroke/>

useOffsetPagination
===================




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 650 B |
|  Last Changed  | 2 weeks ago |


Reactive offset pagination.


Usage
-----




```
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,
  onPageChange: fetchData,
  onPageSizeChange: fetchData,
})
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<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:




```
<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:




```
<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>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseOffsetPaginationOptions {
  /**
   * Total number of items.
   */
  total?: MaybeRefOrGetter<number>
  /**
   * The number of items to display per page.
   * @default 10
   */
  pageSize?: MaybeRefOrGetter<number>
  /**
   * The current page number.
   * @default 1
   */
  page?: MaybeRef<number>
  /**
   * Callback when the `page` change.
   */
  onPageChange?: (
    returnValue: UnwrapNestedRefs<UseOffsetPaginationReturn>
  ) => unknown
  /**
   * Callback when the `pageSize` change.
   */
  onPageSizeChange?: (
    returnValue: UnwrapNestedRefs<UseOffsetPaginationReturn>
  ) => unknown
  /**
   * Callback when the `pageCount` change.
   */
  onPageCountChange?: (
    returnValue: UnwrapNestedRefs<UseOffsetPaginationReturn>
  ) => unknown
}
export interface UseOffsetPaginationReturn {
  currentPage: Ref<number>
  currentPageSize: Ref<number>
  pageCount: ComputedRef<number>
  isFirstPage: ComputedRef<boolean>
  isLastPage: ComputedRef<boolean>
  prev: () => void
  next: () => void
}
export type UseOffsetPaginationInfinityPageReturn = Omit<
  UseOffsetPaginationReturn,
  "isLastPage"
>
export declare function useOffsetPagination(
  options: Omit<UseOffsetPaginationOptions, "total">
): UseOffsetPaginationInfinityPageReturn
export declare function useOffsetPagination(
  options: UseOffsetPaginationOptions
): UseOffsetPaginationReturn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useOffsetPagination/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useOffsetPagination/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useOffsetPagination/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useOffsetPagination/>

useElementByPoint
=================




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 642 B |
|  Last Changed  | 2 weeks ago |


Reactive element by point.


Usage
-----




```
import { useElementByPoint, useMouse } from '@vueuse/core'

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


Type Declarations
-----------------




```
export interface UseElementByPointOptions extends ConfigurableDocument {
  x: MaybeRefOrGetter<number>
  y: MaybeRefOrGetter<number>
}
/**
 * Reactive element by point.
 *
 * @see https://vueuse.org/useElementByPoint
 * @param options - UseElementByPointOptions
 */
export declare function useElementByPoint(options: UseElementByPointOptions): {
  isActive: Readonly<Ref<boolean>>
  pause: Fn
  resume: Fn
  element: Ref<HTMLElement | null>
}
export type UseElementByPointReturn = ReturnType<typeof useElementByPoint>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementByPoint/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementByPoint/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementByPoint/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useElementByPoint/>

useNavigatorLanguage
====================




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 632 B |
|  Last Changed  | 4 weeks ago |


Reactive [navigator.language](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language).


Usage
-----




```
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,
    }
  },
})
```


Type Declarations
-----------------



Show Type Declarations

```
export interface NavigatorLanguageState {
  isSupported: Ref<boolean>
  /**
   *
   * ISO 639-1 standard Language Code
   *
   * @info The detected user agent language preference as a language tag
   * (which is sometimes referred to as a "locale identifier").
   * This consists of a 2-3 letter base language tag that indicates a
   * language, optionally followed by additional subtags separated by
   * '-'. The most common extra information is the country or region
   * variant (like 'en-US' or 'fr-CA').
   *
   *
   * @see https://www.iso.org/iso-639-language-codes.html
   * @see https://www.loc.gov/standards/iso639-2/php/code_list.php
   *
   */
  language: Ref<string | undefined>
}
/**
 *
 * Reactive useNavigatorLanguage
 *
 * Detects the currently selected user language and returns a reactive language
 * @see https://vueuse.org/useNavigatorLanguage
 *
 */
export declare function useNavigatorLanguage(
  options?: ConfigurableWindow
): Readonly<NavigatorLanguageState>
export type UseNavigatorLanguageReturn = ReturnType<typeof useNavigatorLanguage>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useNavigatorLanguage/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useNavigatorLanguage/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useNavigatorLanguage/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useNavigatorLanguage/>

useDropZone
===========




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 629 B |
|  Last Changed  | 2 weeks ago |


Create a zone where files can be dropped.


Usage
-----




```
<script setup lang="ts">
import { useDropZone } from '@vueuse/core'

const dropZoneRef = ref<HTMLDivElement>()

function onDrop(files: File[] | null) {
  // called when files are dropped on zone
}

const { isOverDropZone } = useDropZone(dropZoneRef, onDrop)
</script>

<template>
  <div ref="dropZoneRef">
    Drop files here
  </div>
</template>
```


Type Declarations
-----------------




```
export interface UseDropZoneReturn {
  isOverDropZone: Ref<boolean>
}
export declare function useDropZone(
  target: MaybeRefOrGetter<HTMLElement | null | undefined>,
  onDrop?: (files: File[] | null) => void
): UseDropZoneReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDropZone/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDropZone/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDropZone/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDropZone/>

useElementVisibility
====================




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 626 B |
|  Last Changed  | 2 weeks ago |


Tracks the visibility of an element within the viewport.


Usage
-----




```
<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](../../guide/components). 
> 
> 




```
<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](../../guide/components). 
> 
> 




```
<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>
```


Type Declarations
-----------------




```
export interface UseElementVisibilityOptions extends ConfigurableWindow {
  scrollTarget?: MaybeRefOrGetter<HTMLElement | undefined | null>
}
/**
 * Tracks the visibility of an element within the viewport.
 *
 * @see https://vueuse.org/useElementVisibility
 * @param element
 * @param options
 */
export declare function useElementVisibility(
  element: MaybeComputedElementRef,
  { window, scrollTarget }?: UseElementVisibilityOptions
): Ref<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementVisibility/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementVisibility/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementVisibility/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useElementVisibility/>

useMutationObserver
===================




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 612 B |
|  Last Changed  | 9 months ago |


Watch for changes being made to the DOM tree. [MutationObserver MDN](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)


Usage
-----




```
import { ref } from 'vue'
import { useMutationObserver } from '@vueuse/core'

export default {
  setup() {
    const el = ref(null)
    const messages = ref([])

    useMutationObserver(el, (mutations) => {
      if (mutations[0])
        messages.value.push(mutations[0].attributeName)
    }, {
      attributes: true,
    })

    return {
      el,
      messages,
    }
  },
}
```


Type Declarations
-----------------




```
export interface UseMutationObserverOptions
  extends MutationObserverInit,
    ConfigurableWindow {}
/**
 * Watch for changes being made to the DOM tree.
 *
 * @see https://vueuse.org/useMutationObserver
 * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver MDN
 * @param target
 * @param callback
 * @param options
 */
export declare function useMutationObserver(
  target: MaybeElementRef,
  callback: MutationCallback,
  options?: UseMutationObserverOptions
): {
  isSupported: ComputedRef<boolean>
  stop: () => void
}
export type UseMutationObserverReturn = ReturnType<typeof useMutationObserver>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMutationObserver/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMutationObserver/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMutationObserver/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMutationObserver/>

useElementHover
===============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 598 B |
|  Last Changed  | 2 weeks ago |


Reactive element's hover state.


Usage
-----




```
<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](../../guide/components). 
> 
> 




```
<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>
```


Type Declarations
-----------------




```
export interface UseElementHoverOptions extends ConfigurableWindow {
  delayEnter?: number
  delayLeave?: number
}
export declare function useElementHover(
  el: MaybeRefOrGetter<EventTarget | null | undefined>,
  options?: UseElementHoverOptions
): Ref<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementHover/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementHover/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useElementHover/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useElementHover/>

useFocus
========




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 605 B |
|  Last Changed  | 3 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.


Basic Usage
-----------




```
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.




```
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).




```
<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>
```


Type Declarations
-----------------




```
export interface UseFocusOptions extends ConfigurableWindow {
  /**
   * Initial value. If set true, then focus will be set on the target
   *
   * @default false
   */
  initialValue?: boolean
}
export interface UseFocusReturn {
  /**
   * If read as true, then the element has focus. If read as false, then the element does not have focus
   * If set to true, then the element will be focused. If set to false, the element will be blurred.
   */
  focused: Ref<boolean>
}
/**
 * Track or set the focus state of a DOM element.
 *
 * @see https://vueuse.org/useFocus
 * @param target The target element for the focus and blur events.
 * @param options
 */
export declare function useFocus(
  target: MaybeElementRef,
  options?: UseFocusOptions
): UseFocusReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useFocus/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useFocus/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useFocus/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useFocus/>

useBluetooth
============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 596 B |
|  Last Changed  | 6 months ago |


Reactive [Web Bluetooth API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API). Provides the ability to connect and interact with Bluetooth Low Energy peripherals.


The Web Bluetooth API lets websites discover and communicate with devices over the Bluetooth 4 wireless standard using the Generic Attribute Profile (GATT).


N.B. It is currently partially implemented in Android M, Chrome OS, Mac, and Windows 10. For a full overview of browser compatibility please see [Web Bluetooth API Browser Compatibility](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API#browser_compatibility)


N.B. There are a number of caveats to be aware of with the web bluetooth API specification. Please refer to the [Web Bluetooth W3C Draft Report](https://webbluetoothcg.github.io/web-bluetooth/) for numerous caveats around device detection and connection.


N.B. This API is not available in Web Workers (not exposed via WorkerNavigator).


Usage Default
-------------




```
import { useBluetooth } from '@vueuse/core'

const {
  isSupported,
  isConnected,
  device,
  requestDevice,
  server,
} = useBluetooth({
  acceptAllDevices: true,
})
```




```
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>
```


When the device has paired and is connected, you can then work with the server object as you wish.


Usage Battery Level Example
---------------------------


This sample illustrates the use of the Web Bluetooth API to read battery level and be notified of changes from a nearby Bluetooth Device advertising Battery information with Bluetooth Low Energy.


Here, we use the characteristicvaluechanged event listener to handle reading battery level characteristic value. This event listener will optionally handle upcoming notifications as well.




```
import { pausableWatch, useBluetooth } from '@vueuse/core'

const {
  isSupported,
  isConnected,
  device,
  requestDevice,
  server,
} = useBluetooth({
  acceptAllDevices: true,
  optionalServices: [
    'battery_service',
  ],
})

const batteryPercent = ref<undefined | number>()

const isGettingBatteryLevels = ref(false)

async function getBatteryLevels() {
  isGettingBatteryLevels.value = true

  // Get the battery service:
  const batteryService = await server.getPrimaryService('battery_service')

  // Get the current battery level
  const batteryLevelCharacteristic = await batteryService.getCharacteristic(
    'battery_level',
  )

  // Listen to when characteristic value changes on `characteristicvaluechanged` event:
  batteryLevelCharacteristic.addEventListener('characteristicvaluechanged', (event) => {
    batteryPercent.value = event.target.value.getUint8(0)
  })

  // Convert received buffer to number:
  const batteryLevel = await batteryLevelCharacteristic.readValue()

  batteryPercent.value = await batteryLevel.getUint8(0)
}

const { stop } = pausableWatch(isConnected, (newIsConnected) => {
  if (!newIsConnected || !server.value || isGettingBatteryLevels.value)
    return
  // Attempt to get the battery levels of the device:
  getBatteryLevels()
  // We only want to run this on the initial connection, as we will use an event listener to handle updates:
  stop()
})
```




```
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>
```


More samples can be found on [Google Chrome's Web Bluetooth Samples](https://googlechrome.github.io/samples/web-bluetooth/).


Type Declarations
-----------------



Show Type Declarations

```
/// <reference types="@types/web-bluetooth" />
export interface UseBluetoothRequestDeviceOptions {
  /**
   *
   * An array of BluetoothScanFilters. This filter consists of an array
   * of BluetoothServiceUUIDs, a name parameter, and a namePrefix parameter.
   *
   */
  filters?: BluetoothLEScanFilter[] | undefined
  /**
   *
   * An array of BluetoothServiceUUIDs.
   *
   * @see https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTService/uuid
   *
   */
  optionalServices?: BluetoothServiceUUID[] | undefined
}
export interface UseBluetoothOptions
  extends UseBluetoothRequestDeviceOptions,
    ConfigurableNavigator {
  /**
   *
   * A boolean value indicating that the requesting script can accept all Bluetooth
   * devices. The default is false.
   *
   * !! This may result in a bunch of unrelated devices being shown
   * in the chooser and energy being wasted as there are no filters.
   *
   *
   * Use it with caution.
   *
   * @default false
   *
   */
  acceptAllDevices?: boolean
}
export declare function useBluetooth(
  options?: UseBluetoothOptions
): UseBluetoothReturn
export interface UseBluetoothReturn {
  isSupported: Ref<boolean>
  isConnected: ComputedRef<boolean>
  device: Ref<BluetoothDevice | undefined>
  requestDevice: () => Promise<void>
  server: Ref<BluetoothRemoteGATTServer | undefined>
  error: Ref<unknown | null>
}
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useBluetooth/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useBluetooth/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useBluetooth/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useBluetooth/>

usePreferredContrast
====================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 583 B |
|  Last Changed  | 8 months ago |


Reactive [prefers-contrast](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-contrast) media query.


Usage
-----




```
import { usePreferredContrast } from '@vueuse/core'

const preferredContrast = usePreferredContrast()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UsePreferredContrast v-slot="{ contrast }">
  Preferred Contrast: {{ contrast }}
</UsePreferredContrast>
```


Type Declarations
-----------------




```
export type ContrastType = "more" | "less" | "custom" | "no-preference"
/**
 * Reactive prefers-contrast media query.
 *
 * @see https://vueuse.org/usePreferredContrast
 * @param [options]
 */
export declare function usePreferredContrast(
  options?: ConfigurableWindow
): ComputedRef<ContrastType>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredContrast/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredContrast/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredContrast/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePreferredContrast/>

useVModels
==========




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 562 B |
|  Last Changed  | 9 months ago |
|  Related  | [`useVModel`](../usevmodel/index) |


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


Usage
-----




```
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')
  },
}
```


Type Declarations
-----------------




```
/**
 * Shorthand for props v-model binding. Think like `toRefs(props)` but changes will also emit out.
 *
 * @see https://vueuse.org/useVModels
 * @param props
 * @param emit
 */
export declare function useVModels<P extends object, Name extends string>(
  props: P,
  emit?: (name: Name, ...args: any[]) => void,
  options?: UseVModelOptions<any>
): ToRefs<P>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useVModels/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useVModels/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useVModels/>

useKeyModifier
==============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 587 B |
|  Last Changed  | 10 months ago |


Reactive [Modifier State](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState). Tracks state of any of the [supported modifiers](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState#browser_compatibility) - see Browser Compatibility notes.


[Learn useKeyModifier with this FREE video lesson from Vue School!](https://vueschool.io/lessons/alt-drag-to-clone-tasks?friend=vueuse)Usage
-----




```
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:




```
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:




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


Type Declarations
-----------------




```
export type KeyModifier =
  | "Alt"
  | "AltGraph"
  | "CapsLock"
  | "Control"
  | "Fn"
  | "FnLock"
  | "Meta"
  | "NumLock"
  | "ScrollLock"
  | "Shift"
  | "Symbol"
  | "SymbolLock"
export interface UseModifierOptions<Initial> extends ConfigurableDocument {
  /**
   * Event names that will prompt update to modifier states
   *
   * @default ['mousedown', 'mouseup', 'keydown', 'keyup']
   */
  events?: WindowEventName[]
  /**
   * Initial value of the returned ref
   *
   * @default null
   */
  initial?: Initial
}
export type UseKeyModifierReturn<Initial> = Ref<
  Initial extends boolean ? boolean : boolean | null
>
export declare function useKeyModifier<Initial extends boolean | null>(
  modifier: KeyModifier,
  options?: UseModifierOptions<Initial>
): UseKeyModifierReturn<Initial>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useKeyModifier/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useKeyModifier/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useKeyModifier/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useKeyModifier/>

usePageLeave
============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 576 B |
|  Last Changed  | last year |


Reactive state to show whether the mouse leaves the page.


Usage
-----




```
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](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
/**
 * Reactive state to show whether mouse leaves the page.
 *
 * @see https://vueuse.org/usePageLeave
 * @param options
 */
export declare function usePageLeave(options?: ConfigurableWindow): Ref<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePageLeave/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePageLeave/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePageLeave/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePageLeave/>

usePreferredColorScheme
=======================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 570 B |
|  Last Changed  | last year |


Reactive [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) media query.


Usage
-----




```
import { usePreferredColorScheme } from '@vueuse/core'

const preferredColor = usePreferredColorScheme()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export type ColorSchemeType = "dark" | "light" | "no-preference"
/**
 * Reactive prefers-color-scheme media query.
 *
 * @see https://vueuse.org/usePreferredColorScheme
 * @param [options]
 */
export declare function usePreferredColorScheme(
  options?: ConfigurableWindow
): ComputedRef<ColorSchemeType>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredColorScheme/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredColorScheme/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredColorScheme/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePreferredColorScheme/>

usePreferredReducedMotion
=========================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 557 B |
|  Last Changed  | 9 months ago |


Reactive [prefers-reduced-motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion) media query.


Usage
-----




```
import { usePreferredReducedMotion } from '@vueuse/core'

const preferredMotion = usePreferredReducedMotion()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export type ReducedMotionType = "reduce" | "no-preference"
/**
 * Reactive prefers-reduced-motion media query.
 *
 * @see https://vueuse.org/usePreferredReducedMotion
 * @param [options]
 */
export declare function usePreferredReducedMotion(
  options?: ConfigurableWindow
): ComputedRef<ReducedMotionType>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredReducedMotion/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredReducedMotion/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredReducedMotion/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePreferredReducedMotion/>

useIntersectionObserver
=======================




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 572 B |
|  Last Changed  | last week |


Detects that a target element's visibility.


Usage
-----




```
<div ref="target">
  <h1>Hello world</h1>
</div>
```




```
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'

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

    const { stop } = useIntersectionObserver(
      target,
      ([{ isIntersecting }], observerElement) => {
        targetIsVisible.value = isIntersecting
      },
    )

    return {
      target,
      targetIsVisible,
    }
  },
}
```


Directive Usage
---------------



>  This function also provides a directive version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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

const root = ref(null)

const isVisible = ref(false)

function onIntersectionObserver([{ isIntersecting }]) {
  isVisible.value = isIntersecting
}

</script>

<template>
  <div>
    <p>
      Scroll me down!
    </p>
    <div v-intersection-observer="onIntersectionObserver">
      <p>Hello world!</p>
    </div>
  </div>

  <!-- with options -->
  <div ref="root">
    <p>
      Scroll me down!
    </p>
    <div v-intersection-observer="[onIntersectionObserver, { root }]">
      <p>Hello world!</p>
    </div>
  </div>
</template>
```


[IntersectionObserver MDN](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver)


Type Declarations
-----------------



Show Type Declarations

```
export interface UseIntersectionObserverOptions extends ConfigurableWindow {
  /**
   * Start the IntersectionObserver immediately on creation
   *
   * @default true
   */
  immediate?: boolean
  /**
   * The Element or Document whose bounds are used as the bounding box when testing for intersection.
   */
  root?: MaybeComputedElementRef
  /**
   * A string which specifies a set of offsets to add to the root's bounding_box when calculating intersections.
   */
  rootMargin?: string
  /**
   * Either a single number or an array of numbers between 0.0 and 1.
   */
  threshold?: number | number[]
}
export interface UseIntersectionObserverReturn extends Pausable {
  isSupported: Ref<boolean>
  stop: () => void
}
/**
 * Detects that a target element's visibility.
 *
 * @see https://vueuse.org/useIntersectionObserver
 * @param target
 * @param callback
 * @param options
 */
export declare function useIntersectionObserver(
  target:
    | MaybeComputedElementRef
    | MaybeRefOrGetter<MaybeElement[]>
    | MaybeComputedElementRef[],
  callback: IntersectionObserverCallback,
  options?: UseIntersectionObserverOptions
): UseIntersectionObserverReturn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useIntersectionObserver/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useIntersectionObserver/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useIntersectionObserver/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useIntersectionObserver/>

useWindowScroll
===============




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 555 B |
|  Last Changed  | 2 months ago |


Reactive window scroll


Usage
-----




```
import { useWindowScroll } from '@vueuse/core'

const { x, y } = useWindowScroll()
```


Type Declarations
-----------------




```
/**
 * Reactive window scroll.
 *
 * @see https://vueuse.org/useWindowScroll
 * @param options
 */
export declare function useWindowScroll({ window }?: ConfigurableWindow): {
  x: Ref<number>
  y: Ref<number>
}
export type UseWindowScrollReturn = ReturnType<typeof useWindowScroll>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useWindowScroll/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useWindowScroll/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useWindowScroll/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useWindowScroll/>

useDocumentVisibility
=====================




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 542 B |
|  Last Changed  | 9 months ago |


Reactively track [`document.visibilityState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState)


Usage
-----




```
import { useDocumentVisibility } from '@vueuse/core'

const visibility = useDocumentVisibility()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseDocumentVisibility v-slot="{ visibility }">
  Document Visibility: {{ visibility }}
</UseDocumentVisibility>
```


Type Declarations
-----------------




```
/**
 * Reactively track `document.visibilityState`.
 *
 * @see https://vueuse.org/useDocumentVisibility
 * @param options
 */
export declare function useDocumentVisibility({
  document,
}?: ConfigurableDocument): Ref<DocumentVisibilityState>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDocumentVisibility/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDocumentVisibility/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDocumentVisibility/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDocumentVisibility/>

usePreferredLanguages
=====================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 537 B |
|  Last Changed  | last year |


Reactive [Navigator Languages](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages). It provides web developers with information about the user's preferred languages. For example, this may be useful to adjust the language of the user interface based on the user's preferred languages in order to provide better experience.


Usage
-----




```
import { usePreferredLanguages } from '@vueuse/core'

const languages = usePreferredLanguages()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UsePreferredLanguages v-slot="{ languages }">
  Preferred Languages: {{ languages }}
</UsePreferredLanguages>
```


Type Declarations
-----------------




```
/**
 * Reactive Navigator Languages.
 *
 * @see https://vueuse.org/usePreferredLanguages
 * @param options
 */
export declare function usePreferredLanguages(
  options?: ConfigurableWindow
): Ref<readonly string[]>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredLanguages/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredLanguages/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredLanguages/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePreferredLanguages/>

usePreferredDark
================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 536 B |
|  Last Changed  | last year |
|  Related  | [`useColorMode`](../usecolormode/index)[`useDark`](../usedark/index) |


Reactive dark theme preference.


Usage
-----




```
import { usePreferredDark } from '@vueuse/core'

const isDark = usePreferredDark()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UsePreferredDark v-slot="{ prefersDark }">
  Prefers Dark: {{ prefersDark }}
</UsePreferredDark>
```


Type Declarations
-----------------




```
/**
 * Reactive dark theme preference.
 *
 * @see https://vueuse.org/usePreferredDark
 * @param [options]
 */
export declare function usePreferredDark(
  options?: ConfigurableWindow
): Ref<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredDark/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredDark/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePreferredDark/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePreferredDark/>

useUserMedia
============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 569 B |
|  Last Changed  | 2 weeks ago |
|  Related  | [`useDevicesList`](../usedeviceslist/index)[`useDisplayMedia`](../usedisplaymedia/index)[`usePermission`](../usepermission/index) |


Reactive [`mediaDevices.getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) streaming.


Usage
-----




```
import { useUserMedia } from '@vueuse/core'

const { stream, start } = useUserMedia()

start()
```




```
const video = document.getElementById('video')

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


### Devices




```
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, }
  }
})
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseUserMediaOptions extends ConfigurableNavigator {
  /**
   * If the stream is enabled
   * @default false
   */
  enabled?: MaybeRef<boolean>
  /**
   * Recreate stream when deviceIds or constraints changed
   *
   * @default true
   */
  autoSwitch?: MaybeRef<boolean>
  /**
   * MediaStreamConstraints to be applied to the requested MediaStream
   * If provided, the constraints will override videoDeviceId and audioDeviceId
   *
   * @default {}
   */
  constraints?: MaybeRef<MediaStreamConstraints>
}
/**
 * Reactive `mediaDevices.getUserMedia` streaming
 *
 * @see https://vueuse.org/useUserMedia
 * @param options
 */
export declare function useUserMedia(options?: UseUserMediaOptions): {
  isSupported: ComputedRef<boolean>
  stream: Ref<MediaStream | undefined>
  start: () => Promise<MediaStream | undefined>
  stop: () => void
  restart: () => Promise<MediaStream | undefined>
  constraints: Ref<
    | MediaStreamConstraints
    | {
        audio?:
          | boolean
          | {
              advanced?:
                | {
                    aspectRatio?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    autoGainControl?:
                      | boolean
                      | {
                          exact?: boolean | undefined
                          ideal?: boolean | undefined
                        }
                      | undefined
                    channelCount?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    deviceId?:
                      | string
                      | string[]
                      | {
                          exact?: string | string[] | undefined
                          ideal?: string | string[] | undefined
                        }
                      | undefined
                    displaySurface?:
                      | string
                      | string[]
                      | {
                          exact?: string | string[] | undefined
                          ideal?: string | string[] | undefined
                        }
                      | undefined
                    echoCancellation?:
                      | boolean
                      | {
                          exact?: boolean | undefined
                          ideal?: boolean | undefined
                        }
                      | undefined
                    facingMode?:
                      | string
                      | string[]
                      | {
                          exact?: string | string[] | undefined
                          ideal?: string | string[] | undefined
                        }
                      | undefined
                    frameRate?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    groupId?:
                      | string
                      | string[]
                      | {
                          exact?: string | string[] | undefined
                          ideal?: string | string[] | undefined
                        }
                      | undefined
                    height?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    noiseSuppression?:
                      | boolean
                      | {
                          exact?: boolean | undefined
                          ideal?: boolean | undefined
                        }
                      | undefined
                    sampleRate?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    sampleSize?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    width?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                  }[]
                | undefined
              aspectRatio?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              autoGainControl?:
                | boolean
                | {
                    exact?: boolean | undefined
                    ideal?: boolean | undefined
                  }
                | undefined
              channelCount?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              deviceId?:
                | string
                | string[]
                | {
                    exact?: string | string[] | undefined
                    ideal?: string | string[] | undefined
                  }
                | undefined
              displaySurface?:
                | string
                | string[]
                | {
                    exact?: string | string[] | undefined
                    ideal?: string | string[] | undefined
                  }
                | undefined
              echoCancellation?:
                | boolean
                | {
                    exact?: boolean | undefined
                    ideal?: boolean | undefined
                  }
                | undefined
              facingMode?:
                | string
                | string[]
                | {
                    exact?: string | string[] | undefined
                    ideal?: string | string[] | undefined
                  }
                | undefined
              frameRate?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              groupId?:
                | string
                | string[]
                | {
                    exact?: string | string[] | undefined
                    ideal?: string | string[] | undefined
                  }
                | undefined
              height?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              noiseSuppression?:
                | boolean
                | {
                    exact?: boolean | undefined
                    ideal?: boolean | undefined
                  }
                | undefined
              sampleRate?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              sampleSize?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              width?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
            }
          | undefined
        peerIdentity?: string | undefined
        preferCurrentTab?: boolean | undefined
        video?:
          | boolean
          | {
              advanced?:
                | {
                    aspectRatio?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    autoGainControl?:
                      | boolean
                      | {
                          exact?: boolean | undefined
                          ideal?: boolean | undefined
                        }
                      | undefined
                    channelCount?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    deviceId?:
                      | string
                      | string[]
                      | {
                          exact?: string | string[] | undefined
                          ideal?: string | string[] | undefined
                        }
                      | undefined
                    displaySurface?:
                      | string
                      | string[]
                      | {
                          exact?: string | string[] | undefined
                          ideal?: string | string[] | undefined
                        }
                      | undefined
                    echoCancellation?:
                      | boolean
                      | {
                          exact?: boolean | undefined
                          ideal?: boolean | undefined
                        }
                      | undefined
                    facingMode?:
                      | string
                      | string[]
                      | {
                          exact?: string | string[] | undefined
                          ideal?: string | string[] | undefined
                        }
                      | undefined
                    frameRate?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    groupId?:
                      | string
                      | string[]
                      | {
                          exact?: string | string[] | undefined
                          ideal?: string | string[] | undefined
                        }
                      | undefined
                    height?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    noiseSuppression?:
                      | boolean
                      | {
                          exact?: boolean | undefined
                          ideal?: boolean | undefined
                        }
                      | undefined
                    sampleRate?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    sampleSize?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                    width?:
                      | number
                      | {
                          exact?: number | undefined
                          ideal?: number | undefined
                          max?: number | undefined
                          min?: number | undefined
                        }
                      | undefined
                  }[]
                | undefined
              aspectRatio?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              autoGainControl?:
                | boolean
                | {
                    exact?: boolean | undefined
                    ideal?: boolean | undefined
                  }
                | undefined
              channelCount?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              deviceId?:
                | string
                | string[]
                | {
                    exact?: string | string[] | undefined
                    ideal?: string | string[] | undefined
                  }
                | undefined
              displaySurface?:
                | string
                | string[]
                | {
                    exact?: string | string[] | undefined
                    ideal?: string | string[] | undefined
                  }
                | undefined
              echoCancellation?:
                | boolean
                | {
                    exact?: boolean | undefined
                    ideal?: boolean | undefined
                  }
                | undefined
              facingMode?:
                | string
                | string[]
                | {
                    exact?: string | string[] | undefined
                    ideal?: string | string[] | undefined
                  }
                | undefined
              frameRate?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              groupId?:
                | string
                | string[]
                | {
                    exact?: string | string[] | undefined
                    ideal?: string | string[] | undefined
                  }
                | undefined
              height?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              noiseSuppression?:
                | boolean
                | {
                    exact?: boolean | undefined
                    ideal?: boolean | undefined
                  }
                | undefined
              sampleRate?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              sampleSize?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
              width?:
                | number
                | {
                    exact?: number | undefined
                    ideal?: number | undefined
                    max?: number | undefined
                    min?: number | undefined
                  }
                | undefined
            }
          | undefined
      }
    | undefined
  >
  enabled: Ref<boolean>
  autoSwitch: Ref<boolean>
}
export type UseUserMediaReturn = ReturnType<typeof useUserMedia>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useUserMedia/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useUserMedia/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useUserMedia/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useUserMedia/>

usePerformanceObserver
======================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 536 B |
|  Last Changed  | 2 months ago |


Observe performance metrics.


Usage
-----




```
import { usePerformanceObserver } from '@vueuse/core'

const entrys = ref<PerformanceEntry[]>([])
usePerformanceObserver({
  entryTypes: ['paint'],
}, (list) => {
  entrys.value = list.getEntries()
})
```


Type Declarations
-----------------




```
export type UsePerformanceObserverOptions = PerformanceObserverInit &
  ConfigurableWindow & {
    /**
     * Start the observer immediate.
     *
     * @default true
     */
    immediate?: boolean
  }
/**
 * Observe performance metrics.
 *
 * @see https://vueuse.org/usePerformanceObserver
 * @param options
 */
export declare function usePerformanceObserver(
  options: UsePerformanceObserverOptions,
  callback: PerformanceObserverCallback
): {
  isSupported: ComputedRef<boolean>
  start: () => void
  stop: () => void
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePerformanceObserver/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/usePerformanceObserver/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePerformanceObserver/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePerformanceObserver/>

useWindowFocus
==============




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 532 B |
|  Last Changed  | last year |


Reactively track window focus with `window.onfocus` and `window.onblur` events.


Usage
-----




```
import { useWindowFocus } from '@vueuse/core'

const focused = useWindowFocus()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




```
<UseWindowFocus v-slot="{ focused }">
  Document Focus: {{ focused }}
</UseWindowFocus>
```


Type Declarations
-----------------




```
/**
 * Reactively track window focus with `window.onfocus` and `window.onblur`.
 *
 * @see https://vueuse.org/useWindowFocus
 * @param options
 */
export declare function useWindowFocus({
  window,
}?: ConfigurableWindow): Ref<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useWindowFocus/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useWindowFocus/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useWindowFocus/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useWindowFocus/>

useGeolocation
==============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 526 B |
|  Last Changed  | last month |


Reactive [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/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.


Usage
-----




```
import { useGeolocation } from '@vueuse/core'

const { coords, locatedAt, error, resume, pause } = useGeolocation()
```




| State | Type | Description |
| --- | --- | --- |
| coords | [`Coordinates`](https://developer.mozilla.org/en-US/docs/Web/API/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`](index) function takes [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/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](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export interface UseGeolocationOptions
  extends Partial<PositionOptions>,
    ConfigurableNavigator {
  immediate?: boolean
}
/**
 * Reactive Geolocation API.
 *
 * @see https://vueuse.org/useGeolocation
 * @param options
 */
export declare function useGeolocation(options?: UseGeolocationOptions): {
  isSupported: ComputedRef<boolean>
  coords: Ref<GeolocationCoordinates>
  locatedAt: Ref<number | null>
  error: ShallowRef<GeolocationPositionError | null>
  resume: () => void
  pause: () => void
}
export type UseGeolocationReturn = ReturnType<typeof useGeolocation>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useGeolocation/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useGeolocation/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useGeolocation/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useGeolocation/>

useMemory
=========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 524 B |
|  Last Changed  | 9 months ago |


Reactive Memory Info.


Usage
-----




```
import { useMemory } from '@vueuse/core'

const { isSupported, memory } = useMemory()
```


Type Declarations
-----------------




```
/**
 * Performance.memory
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Performance/memory
 */
export interface MemoryInfo {
  /**
   * The maximum size of the heap, in bytes, that is available to the context.
   */
  readonly jsHeapSizeLimit: number
  /**
   *  The total allocated heap size, in bytes.
   */
  readonly totalJSHeapSize: number
  /**
   * The currently active segment of JS heap, in bytes.
   */
  readonly usedJSHeapSize: number
  [Symbol.toStringTag]: "MemoryInfo"
}
export interface UseMemoryOptions extends UseIntervalFnOptions {
  interval?: number
}
/**
 * Reactive Memory Info.
 *
 * @see https://vueuse.org/useMemory
 * @param options
 */
export declare function useMemory(options?: UseMemoryOptions): {
  isSupported: ComputedRef<boolean>
  memory: Ref<MemoryInfo | undefined>
}
export type UseMemoryReturn = ReturnType<typeof useMemory>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMemory/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMemory/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMemory/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMemory/>

useVModel
=========




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 534 B |
|  Last Changed  | last week |
|  Related  | [`useVModels`](../usevmodels/index) |


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


Usage
-----




```
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>`




```
<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>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseVModelOptions<T> {
  /**
   * When passive is set to `true`, it will use `watch` to sync with props and ref.
   * Instead of relying on the `v-model` or `.sync` to work.
   *
   * @default false
   */
  passive?: boolean
  /**
   * When eventName is set, it's value will be used to overwrite the emit event name.
   *
   * @default undefined
   */
  eventName?: string
  /**
   * Attempting to check for changes of properties in a deeply nested object or array.
   * Apply only when `passive` option is set to `true`
   *
   * @default false
   */
  deep?: boolean
  /**
   * Defining default value for return ref when no value is passed.
   *
   * @default undefined
   */
  defaultValue?: T
  /**
   * Clone the props.
   * Accepts a custom clone function.
   * When setting to `true`, it will use `JSON.parse(JSON.stringify(value))` to clone.
   *
   * @default false
   */
  clone?: boolean | CloneFn<T>
  /**
   * The hook before triggering the emit event can be used for form validation.
   * if false is returned, the emit event will not be triggered.
   *
   * @default undefined
   */
  shouldEmit?: (v: T) => boolean
}
/**
 * Shorthand for v-model binding, props + emit -> ref
 *
 * @see https://vueuse.org/useVModel
 * @param props
 * @param key (default 'value' in Vue 2 and 'modelValue' in Vue 3)
 * @param emit
 */
export declare function useVModel<
  P extends object,
  K extends keyof P,
  Name extends string
>(
  props: P,
  key?: K,
  emit?: (name: Name, ...args: any[]) => void,
  options?: UseVModelOptions<P[K]>
): Ref<UnwrapRef<P[K]>> | WritableComputedRef<P[K]>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useVModel/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useVModel/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useVModel/>

useManualRefHistory
===================




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 516 B |
|  Last Changed  | last week |
|  Related  | [`useRefHistory`](../userefhistory/index) |


Manually track the change history of a ref when the using calls `commit()`, also provides undo and redo functionality


Usage
-----




```
import { ref } from 'vue'
import { useManualRefHistory } from '@vueuse/core'

const counter = ref(0)
const { history, commit, undo, redo } = useManualRefHistory(counter)

counter.value += 1
commit()

console.log(history.value)
/* [
  { snapshot: 1, timestamp: 1601912898062 },
  { snapshot: 0, timestamp: 1601912898061 }
] */
```


You can use `undo` to reset the ref value to the last history point.




```
console.log(counter.value) // 1
undo()
console.log(counter.value) // 0
```


#### History of mutable objects


If you are going to mutate the source, you need to pass a custom clone function or use `clone` `true` as a param, that is a shortcut for a minimal clone function `x => JSON.parse(JSON.stringify(x))` that will be used in both `dump` and `parse`.




```
import { ref } from 'vue'
import { useManualRefHistory } from '@vueuse/core'

const counter = ref({ foo: 1, bar: 2 })
const { history, commit, undo, redo } = useManualRefHistory(counter, { clone: true })

counter.value.foo += 1
commit()
```


#### Custom Clone Function


To use a full featured or custom clone function, you can set up via the `dump` options.


For example, using [structuredClone](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone):




```
import { useManualRefHistory } from '@vueuse/core'

const refHistory = useManualRefHistory(target, { clone: structuredClone })
```


Or by using [lodash's `cloneDeep`](https://lodash.com/docs/4.17.15#cloneDeep):




```
import { cloneDeep } from 'lodash-es'
import { useManualRefHistory } from '@vueuse/core'

const refHistory = useManualRefHistory(target, { clone: cloneDeep })
```


Or a more lightweight [`klona`](https://github.com/lukeed/klona):




```
import { klona } from 'klona'
import { useManualRefHistory } from '@vueuse/core'

const refHistory = useManualRefHistory(target, { clone: klona })
```


#### Custom Dump and Parse Function


Instead of using the `clone` param, you can pass custom functions to control the serialization and parsing. In case you do not need history values to be objects, this can save an extra clone when undoing. It is also useful in case you want to have the snapshots already stringified to be saved to local storage for example.




```
import { useManualRefHistory } from '@vueuse/core'

const refHistory = useManualRefHistory(target, {
  dump: JSON.stringify,
  parse: JSON.parse,
})
```


### History Capacity


We will keep all the history by default (unlimited) until you explicitly clear them up, you can set the maximal amount of history to be kept by `capacity` options.




```
const refHistory = useManualRefHistory(target, {
  capacity: 15, // limit to 15 history records
})

refHistory.clear() // explicitly clear all the history
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseRefHistoryRecord<T> {
  snapshot: T
  timestamp: number
}
export interface UseManualRefHistoryOptions<Raw, Serialized = Raw> {
  /**
   * Maximum number of history to be kept. Default to unlimited.
   */
  capacity?: number
  /**
   * Clone when taking a snapshot, shortcut for dump: JSON.parse(JSON.stringify(value)).
   * Default to false
   *
   * @default false
   */
  clone?: boolean | CloneFn<Raw>
  /**
   * Serialize data into the history
   */
  dump?: (v: Raw) => Serialized
  /**
   * Deserialize data from the history
   */
  parse?: (v: Serialized) => Raw
  /**
   * set data source
   */
  setSource?: (source: Ref<Raw>, v: Raw) => void
}
export interface UseManualRefHistoryReturn<Raw, Serialized> {
  /**
   * Bypassed tracking ref from the argument
   */
  source: Ref<Raw>
  /**
   * An array of history records for undo, newest comes to first
   */
  history: Ref<UseRefHistoryRecord<Serialized>[]>
  /**
   * Last history point, source can be different if paused
   */
  last: Ref<UseRefHistoryRecord<Serialized>>
  /**
   * Same as {@link UseManualRefHistoryReturn.history | history}
   */
  undoStack: Ref<UseRefHistoryRecord<Serialized>[]>
  /**
   * Records array for redo
   */
  redoStack: Ref<UseRefHistoryRecord<Serialized>[]>
  /**
   * A ref representing if undo is possible (non empty undoStack)
   */
  canUndo: Ref<boolean>
  /**
   * A ref representing if redo is possible (non empty redoStack)
   */
  canRedo: Ref<boolean>
  /**
   * Undo changes
   */
  undo: () => void
  /**
   * Redo changes
   */
  redo: () => void
  /**
   * Clear all the history
   */
  clear: () => void
  /**
   * Create new a new history record
   */
  commit: () => void
  /**
   * Reset ref's value with latest history
   */
  reset: () => void
}
/**
 * Track the change history of a ref, also provides undo and redo functionality.
 *
 * @see https://vueuse.org/useManualRefHistory
 * @param source
 * @param options
 */
export declare function useManualRefHistory<Raw, Serialized = Raw>(
  source: Ref<Raw>,
  options?: UseManualRefHistoryOptions<Raw, Serialized>
): UseManualRefHistoryReturn<Raw, Serialized>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useManualRefHistory/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useManualRefHistory/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useManualRefHistory/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useManualRefHistory/>

useCloned
=========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 499 B |
|  Last Changed  | 2 weeks ago |


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


Usage
-----




```
import { useCloned } from '@vueuse/core'

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

const { cloned } = useCloned(original)

original.key = 'some new value'

console.log(cloned.value.key) // 'some new value'
```


Manual cloning
--------------




```
import { useCloned } from '@vueuse/core'

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

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

original.key = 'manual'

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

sync()

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


Custom Clone Function
---------------------


Using [`klona`](https://www.npmjs.com/package/klona) for example:




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

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

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


Type Declarations
-----------------




```
export interface UseClonedOptions<T = any> extends WatchOptions {
  /**
   * Custom clone function.
   *
   * By default, it use `JSON.parse(JSON.stringify(value))` to clone.
   */
  clone?: (source: T) => T
  /**
   * Manually sync the ref
   *
   * @default false
   */
  manual?: boolean
}
export interface UseClonedReturn<T> {
  /**
   * Cloned ref
   */
  cloned: ComputedRef<T>
  /**
   * Sync cloned data with source manually
   */
  sync: () => void
}
export type CloneFn<F, T = F> = (x: F) => T
export declare function cloneFnJSON<T>(source: T): T
export declare function useCloned<T>(
  source: MaybeRefOrGetter<T>,
  options?: UseClonedOptions
): {
  cloned: Ref<UnwrapRef<T>>
  sync: () => void
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useCloned/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useCloned/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useCloned/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useCloned/>

useMediaQuery
=============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 505 B |
|  Last Changed  | 2 weeks ago |


Reactive [Media Query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries). Once you've created a MediaQueryList object, you can check the result of the query or receive notifications when the result changes.


Usage
-----




```
import { useMediaQuery } from '@vueuse/core'

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


Type Declarations
-----------------




```
/**
 * Reactive Media Query.
 *
 * @see https://vueuse.org/useMediaQuery
 * @param query
 * @param options
 */
export declare function useMediaQuery(
  query: MaybeRefOrGetter<string>,
  options?: ConfigurableWindow
): Ref<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMediaQuery/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMediaQuery/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMediaQuery/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMediaQuery/>

createTemplatePromise
=====================




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 497 B |
|  Last Changed  | last week |


Template as Promise. Useful for constructing custom Dialogs, Modals, Toasts, etc.



**WARNING**This function only works for Vue 3



Usage
-----




```
<script setup lang="ts">
import { createTemplatePromise } from '@vueuse/core'

const TemplatePromise = createTemplatePromise<ReturnType>()

async function open() {
  const result = await TemplatePromise.start()
  // button is clicked, result is 'ok'
}
</script>

<template>
  <TemplatePromise v-slot="{ promise, resolve, reject, args }">
    <!-- your UI -->
    <button @click="resolve('ok')">OK</button>
  </TemplatePromise>
</template>
```


Features
--------


* **Programmatic** - call your UI as a promise
* **Template** - use Vue template to render, not a new DSL
* **TypeScript** - full type safety via generic type
* **Renderless** - you take full control of the UI
* **Transition** - use support Vue transition


This function is migrated from [vue-template-promise](https://github.com/antfu/vue-template-promise)


Usage
-----


[`createTemplatePromise`](index) returns a **Vue Component** that you can directly use in your template with `<script setup>`




```
import { createTemplatePromise } from '@vueuse/core'

const TemplatePromise = createTemplatePromise()
const MyPromise = createTemplatePromise<boolean>() // with generic type
```


In template, use `v-slot` to access the promise and resolve functions.




```
<template>
  <TemplatePromise v-slot="{ promise, resolve, reject, args }">
    <!-- you can have anything -->
    <button @click="resolve('ok')">OK</button>
  </TemplatePromise>
  <MyPromise v-slot="{ promise, resolve, reject, args }">
    <!-- another one -->
  </MyPromise>
</template>
```


The slot will not be rendered initially (similar to `v-if="false"`), until you call the `start` method from the component.




```
const result = await TemplatePromise.start()
```


Once `resolve` or `reject` is called in the template, the promise will be resolved or rejected, returning the value you passed in. Once resolved, the slot will be removed automatically.


### Passing Arguments


You can pass arguments to the `start` with arguments.




```
import { createTemplatePromise } from '@vueuse/core'

const TemplatePromise = createTemplatePromise<boolean, [string, number]>()
```




```
const result = await TemplatePromise.start('hello', 123) // Pr
```


And in the template slot, you can access the arguments via `args` property.




```
<template>
  <TemplatePromise v-slot="{ args, resolve }">
    <div>{{ args[0] }}</div> <!-- hello -->
    <div>{{ args[1] }}</div> <!-- 123 -->
    <button @click="resolve(true)">OK</button>
  </TemplatePromise>
</template>
```


### Transition


You can use transition to animate the slot.




```
<script setup lang="ts">
const TemplatePromise = createTemplatePromise<ReturnType>({
  transition: {
    name: 'fade',
    appear: true,
  },
})
</script>

<template>
  <TemplatePromise v-slot="{ resolve }">
    <!-- your UI -->
    <button @click="resolve('ok')">OK</button>
  </TemplatePromise>
</template>

<style scoped>
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>
```


Learn more about [Vue Transition](https://v3.vuejs.org/guide/transitions-overview.html).


Motivation
----------


The common approach to call a dialog or a model programmatically would be like this:




```
const dialog = useDialog()
const result = await dialog.open({
  title: 'Hello',
  content: 'World',
})
```


This would work by sending these information to the top-level component and let it render the dialog. However, it limits the flexibility you could express in the UI. For example, you could want the title to be red, or have extra buttons, etc. You would end up with a lot of options like:




```
const result = await dialog.open({
  title: 'Hello',
  titleClass: 'text-red',
  content: 'World',
  contentClass: 'text-blue text-sm',
  buttons: [
    { text: 'OK', class: 'bg-red', onClick: () => {} },
    { text: 'Cancel', class: 'bg-blue', onClick: () => {} },
  ],
  // ...
})
```


Even this is not flexible enough. If you want more, you might end up with manual render function.




```
const result = await dialog.open({
  title: 'Hello',
  contentSlot: () => h(MyComponent, { content }),
})
```


This is like reinventing a new DSL in the script to express the UI template.


So this function allows **expressing the UI in templates instead of scripts**, where it is supposed to be, while still being able to be manipulated programmatically.


Type Declarations
-----------------



Show Type Declarations

```
export interface TemplatePromiseProps<Return, Args extends any[] = []> {
  /**
   * The promise instance.
   */
  promise: Promise<Return> | undefined
  /**
   * Resolve the promise.
   */
  resolve: (v: Return | Promise<Return>) => void
  /**
   * Reject the promise.
   */
  reject: (v: any) => void
  /**
   * Arguments passed to TemplatePromise.start()
   */
  args: Args
  /**
   * Indicates if the promise is resolving.
   * When passing another promise to `resolve`, this will be set to `true` until the promise is resolved.
   */
  isResolving: boolean
  /**
   * Options passed to createTemplatePromise()
   */
  options: TemplatePromiseOptions
  /**
   * Unique key for list rendering.
   */
  key: number
}
export interface TemplatePromiseOptions {
  /**
   * Determines if the promise can be called only once at a time.
   *
   * @default false
   */
  singleton?: boolean
  /**
   * Transition props for the promise.
   */
  transition?: TransitionGroupProps
}
export type TemplatePromise<
  Return,
  Args extends any[] = []
> = DefineComponent<{}> & {
  new (): {
    $slots: {
      default(_: TemplatePromiseProps<Return, Args>): any
    }
  }
} & {
  start: (...args: Args) => Promise<Return>
}
/**
 * Creates a template promise component.
 *
 * @see https://vueuse.org/createTemplatePromise
 */
export declare function createTemplatePromise<Return, Args extends any[] = []>(
  options?: TemplatePromiseOptions
): TemplatePromise<Return, Args>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/createTemplatePromise/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/createTemplatePromise/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/createTemplatePromise/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/createTemplatePromise/>

useParentElement
================




|  |  |
| --- | --- |
|  Category  | [Elements](../../functions#category=Elements) |
|  Export Size  | 496 B |
|  Last Changed  | 2 weeks ago |


Get parent element of the given element


Usage
-----


When no argument is passed, it will return the parent element of the current component.




```
import { useParentElement } from '@vueuse/core'

const parentEl = useParentElement()

onMounted(() => {
  console.log(parentEl.value)
})
```


It can also accept a `ref` as the first argument.




```
import { useParentElement } from '@vueuse/core'

// Don't forget to bind the ref to the element
const tooltip = ref<HTMLElement | undefined>()

const tooltipWrapper = useParentElement(tooltip)

onMounted(() => {
  console.log(tooltipWrapper.value)
})
```


Type Declarations
-----------------




```
export declare function useParentElement(
  element?: MaybeRefOrGetter<HTMLElement | SVGElement | null | undefined>
): Readonly<Ref<HTMLElement | SVGElement | null | undefined>>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useParentElement/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useParentElement/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useParentElement/>

useBroadcastChannel
===================




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 476 B |
|  Last Changed  | 4 weeks ago |


Reactive [BroadcastChannel API](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel).


Closes a broadcast channel automatically component unmounted.


Usage
-----


The BroadcastChannel interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames, or iframes) of the same origin.


Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel.




```
import { ref } from 'vue'
import { useBroadcastChannel } from '@vueuse/core'

const {
  isSupported,
  channel,
  post,
  close,
  error,
  isClosed,
} = useBroadcastChannel({ name: 'vueuse-demo-channel' })

const message = ref('')

message.value = 'Hello, VueUse World!'

// Post the message to the broadcast channel:
post(message.value)

// Option to close the channel if you wish:
close()
```


Type Declarations
-----------------




```
export interface UseBroadcastChannelOptions extends ConfigurableWindow {
  /**
   * The name of the channel.
   */
  name: string
}
/**
 * Reactive BroadcastChannel
 *
 * @see https://vueuse.org/useBroadcastChannel
 * @see https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
 * @param options
 *
 */
export declare function useBroadcastChannel<D, P>(
  options: UseBroadcastChannelOptions
): UseBroadcastChannelReturn<D, P>
export interface UseBroadcastChannelReturn<D, P> {
  isSupported: Ref<boolean>
  channel: Ref<BroadcastChannel | undefined>
  data: Ref<D>
  post: (data: P) => void
  close: () => void
  error: Ref<Event | null>
  isClosed: Ref<boolean>
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useBroadcastChannel/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useBroadcastChannel/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useBroadcastChannel/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useBroadcastChannel/>

useDisplayMedia
===============




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 476 B |
|  Last Changed  | 4 months ago |
|  Related  | [`useUserMedia`](../useusermedia/index) |


Reactive [`mediaDevices.getDisplayMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia) streaming.


Usage
-----




```
import { useDisplayMedia } from '@vueuse/core'

const { stream, start } = useDisplayMedia()

// start streaming

start()
```




```
const video = document.getElementById('video')

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


Type Declarations
-----------------




```
export interface UseDisplayMediaOptions extends ConfigurableNavigator {
  /**
   * If the stream is enabled
   * @default false
   */
  enabled?: MaybeRef<boolean>
  /**
   * If the stream video media constraints
   */
  video?: boolean | MediaTrackConstraints | undefined
  /**
   * If the stream audio media constraints
   */
  audio?: boolean | MediaTrackConstraints | undefined
}
/**
 * Reactive `mediaDevices.getDisplayMedia` streaming
 *
 * @see https://vueuse.org/useDisplayMedia
 * @param options
 */
export declare function useDisplayMedia(options?: UseDisplayMediaOptions): {
  isSupported: ComputedRef<boolean>
  stream: Ref<MediaStream | undefined>
  start: () => Promise<MediaStream | undefined>
  stop: () => void
  enabled: Ref<boolean>
}
export type UseDisplayMediaReturn = ReturnType<typeof useDisplayMedia>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDisplayMedia/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDisplayMedia/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDisplayMedia/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDisplayMedia/>

useStyleTag
===========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 474 B |
|  Last Changed  | 5 months ago |


Inject reactive `style` element in head.


Usage
-----


### Basic usage


Provide a CSS string, then [`useStyleTag`](index) will automatically generate an id and inject it in `<head>`.




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

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

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


This code will be injected to `<head>`:




```
<style type="text/css" id="vueuse_styletag_1">
.foo { margin-top: 64px; }
</style>
```


### Custom ID


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




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

useStyleTag('.foo { margin-top: 32px; }', { id: 'custom-id' })
```




```
<!-- injected to <head> -->
<style type="text/css" id="custom-id">
.foo { margin-top: 32px; }
</style>
```


### Media query


You can pass media attributes as last argument within object.




```
useStyleTag('.foo { margin-top: 32px; }', { media: 'print' })
```




```
<!-- injected to <head> -->
<style type="text/css" id="vueuse_styletag_1" media="print">
.foo { margin-top: 32px; }
</style>
```


Type Declarations
-----------------




```
export interface UseStyleTagOptions extends ConfigurableDocument {
  /**
   * Media query for styles to apply
   */
  media?: string
  /**
   * Load the style immediately
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Manual controls the timing of loading and unloading
   *
   * @default false
   */
  manual?: boolean
  /**
   * DOM id of the style tag
   *
   * @default auto-incremented
   */
  id?: string
}
export interface UseStyleTagReturn {
  id: string
  css: Ref<string>
  load: () => void
  unload: () => void
  isLoaded: Readonly<Ref<boolean>>
}
/**
 * Inject <style> element in head.
 *
 * Overload: Omitted id
 *
 * @see https://vueuse.org/useStyleTag
 * @param css
 * @param options
 */
export declare function useStyleTag(
  css: MaybeRef<string>,
  options?: UseStyleTagOptions
): UseStyleTagReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useStyleTag/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useStyleTag/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useStyleTag/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useStyleTag/>

useCycleList
============




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 458 B |
|  Last Changed  | 6 days 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!](https://vueschool.io/lessons/create-an-image-carousel-with-vueuse?friend=vueuse)Usage
-----




```
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'
```


Type Declarations
-----------------




```
export interface UseCycleListOptions<T> {
  /**
   * The initial value of the state.
   * A ref can be provided to reuse.
   */
  initialValue?: MaybeRef<T>
  /**
   * The default index when
   */
  fallbackIndex?: number
  /**
   * Custom function to get the index of the current value.
   */
  getIndexOf?: (value: T, list: T[]) => number
}
/**
 * Cycle through a list of items
 *
 * @see https://vueuse.org/useCycleList
 */
export declare function useCycleList<T>(
  list: MaybeRefOrGetter<T[]>,
  options?: UseCycleListOptions<T>
): UseCycleListReturn<T>
export interface UseCycleListReturn<T> {
  state: Ref<T>
  index: Ref<number>
  next: (n?: number) => T
  prev: (n?: number) => T
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useCycleList/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useCycleList/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useCycleList/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useCycleList/>

useStepper
==========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 433 B |
|  Last Changed  | 10 months ago |


Provides helpers for building a multi-step wizard interface.


Usage
-----


### Steps as array




```
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




```
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'
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseStepperReturn<StepName, Steps, Step> {
  /** List of steps. */
  steps: Readonly<Ref<Steps>>
  /** List of step names. */
  stepNames: Readonly<Ref<StepName[]>>
  /** Index of the current step. */
  index: Ref<number>
  /** Current step. */
  current: ComputedRef<Step>
  /** Next step, or undefined if the current step is the last one. */
  next: ComputedRef<StepName | undefined>
  /** Previous step, or undefined if the current step is the first one. */
  previous: ComputedRef<StepName | undefined>
  /** Whether the current step is the first one. */
  isFirst: ComputedRef<boolean>
  /** Whether the current step is the last one. */
  isLast: ComputedRef<boolean>
  /** Get the step at the specified index. */
  at: (index: number) => Step | undefined
  /** Get a step by the specified name. */
  get: (step: StepName) => Step | undefined
  /** Go to the specified step. */
  goTo: (step: StepName) => void
  /** Go to the next step. Does nothing if the current step is the last one. */
  goToNext: () => void
  /** Go to the previous step. Does nothing if the current step is the previous one. */
  goToPrevious: () => void
  /** Go back to the given step, only if the current step is after. */
  goBackTo: (step: StepName) => void
  /** Checks whether the given step is the next step. */
  isNext: (step: StepName) => boolean
  /** Checks whether the given step is the previous step. */
  isPrevious: (step: StepName) => boolean
  /** Checks whether the given step is the current step. */
  isCurrent: (step: StepName) => boolean
  /** Checks if the current step is before the given step. */
  isBefore: (step: StepName) => boolean
  /** Checks if the current step is after the given step. */
  isAfter: (step: StepName) => boolean
}
export declare function useStepper<T extends string | number>(
  steps: MaybeRef<T[]>,
  initialStep?: T
): UseStepperReturn<T, T[], T>
export declare function useStepper<T extends Record<string, any>>(
  steps: MaybeRef<T>,
  initialStep?: keyof T
): UseStepperReturn<Exclude<keyof T, symbol>, T, T[keyof T]>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useStepper/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useStepper/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useStepper/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useStepper/>

useAsyncState
=============




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 424 B |
|  Last Changed  | 2 days ago |


Reactive async state. Will not block your setup function and will trigger changes once the promise is ready.


Usage
-----




```
import axios from 'axios'
import { useAsyncState } from '@vueuse/core'

const { state, isReady, isLoading } = useAsyncState(
  axios
    .get('https://jsonplaceholder.typicode.com/todos/1')
    .then(t => t.data),
  { id: null },
)
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseAsyncStateReturnBase<
  Data,
  Params extends any[],
  Shallow extends boolean
> {
  state: Shallow extends true ? Ref<Data> : Ref<UnwrapRef<Data>>
  isReady: Ref<boolean>
  isLoading: Ref<boolean>
  error: Ref<unknown>
  execute: (delay?: number, ...args: Params) => Promise<Data>
}
export type UseAsyncStateReturn<
  Data,
  Params extends any[],
  Shallow extends boolean
> = UseAsyncStateReturnBase<Data, Params, Shallow> &
  PromiseLike<UseAsyncStateReturnBase<Data, Params, Shallow>>
export interface UseAsyncStateOptions<Shallow extends boolean, D = any> {
  /**
   * Delay for executing the promise. In milliseconds.
   *
   * @default 0
   */
  delay?: number
  /**
   * Execute the promise right after the function is invoked.
   * Will apply the delay if any.
   *
   * When set to false, you will need to execute it manually.
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Callback when error is caught.
   */
  onError?: (e: unknown) => void
  /**
   * Callback when success is caught.
   * @param {D} data
   */
  onSuccess?: (data: D) => void
  /**
   * Sets the state to initialState before executing the promise.
   *
   * This can be useful when calling the execute function more than once (for
   * example, to refresh data). When set to false, the current state remains
   * unchanged until the promise resolves.
   *
   * @default true
   */
  resetOnExecute?: boolean
  /**
   * Use shallowRef.
   *
   * @default true
   */
  shallow?: Shallow
  /**
   *
   * An error is thrown when executing the execute function
   *
   * @default false
   */
  throwError?: boolean
}
/**
 * Reactive async state. Will not block your setup function and will trigger changes once
 * the promise is ready.
 *
 * @see https://vueuse.org/useAsyncState
 * @param promise         The promise / async function to be resolved
 * @param initialState    The initial state, used until the first evaluation finishes
 * @param options
 */
export declare function useAsyncState<
  Data,
  Params extends any[] = [],
  Shallow extends boolean = true
>(
  promise: Promise<Data> | ((...args: Params) => Promise<Data>),
  initialState: Data,
  options?: UseAsyncStateOptions<Shallow, Data>
): UseAsyncStateReturn<Data, Params, Shallow>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useAsyncState/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useAsyncState/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useAsyncState/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useAsyncState/>

useTimeoutPoll
==============




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 407 B |
|  Last Changed  | 2 weeks ago |


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


Usage
-----




```
import { useTimeoutPoll } from '@vueuse/core'

const count = ref(0)

async function fetchData() {
  await promiseTimeout(1000)
  count.value++
}

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


Type Declarations
-----------------




```
export declare function useTimeoutPoll(
  fn: () => Awaitable<void>,
  interval: MaybeRefOrGetter<number>,
  timeoutPollOptions?: UseTimeoutFnOptions
): Pausable
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTimeoutPoll/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTimeoutPoll/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTimeoutPoll/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTimeoutPoll/>

useFps
======




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 458 B |
|  Last Changed  | last year |


Reactive FPS (frames per second).


Usage
-----




```
import { useFps } from '@vueuse/core'

const fps = useFps()
```


Type Declarations
-----------------




```
export interface UseFpsOptions {
  /**
   * Calculate the FPS on every x frames.
   * @default 10
   */
  every?: number
}
export declare function useFps(options?: UseFpsOptions): Ref<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useFps/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useFps/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useFps/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useFps/>

useConfirmDialog
================




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 418 B |
|  Last Changed  | last year |


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.


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




```
<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:




```
<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>
```


Type Declarations
-----------------



Show Type Declarations

```
export type UseConfirmDialogRevealResult<C, D> =
  | {
      data?: C
      isCanceled: false
    }
  | {
      data?: D
      isCanceled: true
    }
export interface UseConfirmDialogReturn<RevealData, ConfirmData, CancelData> {
  /**
   * Revealing state
   */
  isRevealed: ComputedRef<boolean>
  /**
   * Opens the dialog.
   * Create promise and return it. Triggers `onReveal` hook.
   */
  reveal: (
    data?: RevealData
  ) => Promise<UseConfirmDialogRevealResult<ConfirmData, CancelData>>
  /**
   * Confirms and closes the dialog. Triggers a callback inside `onConfirm` hook.
   * Resolves promise from `reveal()` with `data` and `isCanceled` ref with `false` value.
   * Can accept any data and to pass it to `onConfirm` hook.
   */
  confirm: (data?: ConfirmData) => void
  /**
   * Cancels and closes the dialog. Triggers a callback inside `onCancel` hook.
   * Resolves promise from `reveal()` with `data` and `isCanceled` ref with `true` value.
   * Can accept any data and to pass it to `onCancel` hook.
   */
  cancel: (data?: CancelData) => void
  /**
   * Event Hook to be triggered right before dialog creating.
   */
  onReveal: EventHookOn<RevealData>
  /**
   * Event Hook to be called on `confirm()`.
   * Gets data object from `confirm` function.
   */
  onConfirm: EventHookOn<ConfirmData>
  /**
   * Event Hook to be called on `cancel()`.
   * Gets data object from `cancel` function.
   */
  onCancel: EventHookOn<CancelData>
}
/**
 * Hooks for creating confirm dialogs. Useful for modal windows, popups and logins.
 *
 * @see https://vueuse.org/useConfirmDialog/
 * @param revealed `boolean` `ref` that handles a modal window
 */
export declare function useConfirmDialog<
  RevealData = any,
  ConfirmData = any,
  CancelData = any
>(
  revealed?: Ref<boolean>
): UseConfirmDialogReturn<RevealData, ConfirmData, CancelData>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useConfirmDialog/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useConfirmDialog/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useConfirmDialog/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useConfirmDialog/>

useMemoize
==========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 403 B |
|  Last Changed  | 4 weeks 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
-----




```
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:




```
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`




```
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:




```
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
}
```


Type Declarations
-----------------



Show Type Declarations

```
type CacheKey = any
/**
 * Custom memoize cache handler
 */
export interface UseMemoizeCache<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
}
/**
 * Memoized function
 */
export interface UseMemoizeReturn<Result, Args extends unknown[]> {
  /**
   * Get result from cache or call memoized function
   */
  (...args: Args): Result
  /**
   * Call memoized function and update cache
   */
  load(...args: Args): Result
  /**
   * Delete cache of given arguments
   */
  delete(...args: Args): void
  /**
   * Clear cache
   */
  clear(): void
  /**
   * Generate cache key for given arguments
   */
  generateKey(...args: Args): CacheKey
  /**
   * Cache container
   */
  cache: UseMemoizeCache<CacheKey, Result>
}
export interface UseMemoizeOptions<Result, Args extends unknown[]> {
  getKey?: (...args: Args) => string | number
  cache?: UseMemoizeCache<CacheKey, Result>
}
/**
 * Reactive function result cache based on arguments
 */
export declare function useMemoize<Result, Args extends unknown[]>(
  resolver: (...args: Args) => Result,
  options?: UseMemoizeOptions<Result, Args>
): UseMemoizeReturn<Result, Args>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMemoize/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMemoize/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMemoize/>

useAsyncQueue
=============




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 391 B |
|  Last Changed  | last year |


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


Usage
-----




```
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
```


Type Declarations
-----------------



Show Type Declarations

```
export type UseAsyncQueueTask<T> = (...args: any[]) => T | Promise<T>
export interface UseAsyncQueueResult<T> {
  state: "pending" | "fulfilled" | "rejected"
  data: T | null
}
export interface UseAsyncQueueReturn<T> {
  activeIndex: Ref<number>
  result: T
}
export interface UseAsyncQueueOptions {
  /**
   * Interrupt tasks when current task fails.
   *
   * @default true
   */
  interrupt?: boolean
  /**
   * Trigger it when the tasks fails.
   *
   */
  onError?: () => void
  /**
   * Trigger it when the tasks ends.
   *
   */
  onFinished?: () => void
}
/**
 * Asynchronous queue task controller.
 *
 * @see https://vueuse.org/useAsyncQueue
 * @param tasks
 * @param options
 */
export declare function useAsyncQueue<T1>(
  tasks: [UseAsyncQueueTask<T1>],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<[UseAsyncQueueResult<T1>]>
export declare function useAsyncQueue<T1, T2>(
  tasks: [UseAsyncQueueTask<T1>, UseAsyncQueueTask<T2>],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<[UseAsyncQueueResult<T1>, UseAsyncQueueResult<T2>]>
export declare function useAsyncQueue<T1, T2, T3>(
  tasks: [UseAsyncQueueTask<T1>, UseAsyncQueueTask<T2>, UseAsyncQueueTask<T3>],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<
  [UseAsyncQueueResult<T1>, UseAsyncQueueResult<T2>, UseAsyncQueueResult<T3>]
>
export declare function useAsyncQueue<T1, T2, T3, T4>(
  tasks: [
    UseAsyncQueueTask<T1>,
    UseAsyncQueueTask<T2>,
    UseAsyncQueueTask<T3>,
    UseAsyncQueueTask<T4>
  ],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<
  [
    UseAsyncQueueResult<T1>,
    UseAsyncQueueResult<T2>,
    UseAsyncQueueResult<T3>,
    UseAsyncQueueResult<T4>
  ]
>
export declare function useAsyncQueue<T1, T2, T3, T4, T5>(
  tasks: [
    UseAsyncQueueTask<T1>,
    UseAsyncQueueTask<T2>,
    UseAsyncQueueTask<T3>,
    UseAsyncQueueTask<T4>,
    UseAsyncQueueTask<T5>
  ],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<
  [
    UseAsyncQueueResult<T1>,
    UseAsyncQueueResult<T2>,
    UseAsyncQueueResult<T3>,
    UseAsyncQueueResult<T4>,
    UseAsyncQueueResult<T5>
  ]
>
export declare function useAsyncQueue<T>(
  tasks: UseAsyncQueueTask<T>[],
  options?: UseAsyncQueueOptions
): UseAsyncQueueReturn<UseAsyncQueueResult<T>[]>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useAsyncQueue/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useAsyncQueue/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useAsyncQueue/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useAsyncQueue/>

useFavicon
==========




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 362 B |
|  Last Changed  | last week |


Reactive favicon


Usage
-----




```
import { useFavicon } from '@vueuse/core'

const icon = useFavicon()

icon.value = 'dark.png' // change current icon
```


### Passing a source ref


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




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

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

useFavicon(favicon)
```


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




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

console.log(icon === source) // true
```


Type Declarations
-----------------




```
export interface UseFaviconOptions extends ConfigurableDocument {
  baseUrl?: string
  rel?: string
}
/**
 * Reactive favicon.
 *
 * @see https://vueuse.org/useFavicon
 * @param newIcon
 * @param options
 */
export declare function useFavicon(
  newIcon: ReadonlyRefOrGetter<string | null | undefined>,
  options?: UseFaviconOptions
): ComputedRef<string | null | undefined>
export declare function useFavicon(
  newIcon?: MaybeRef<string | null | undefined>,
  options?: UseFaviconOptions
): Ref<string | null | undefined>
export type UseFaviconReturn = ReturnType<typeof useFavicon>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useFavicon/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useFavicon/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useFavicon/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useFavicon/>

useDevicePixelRatio
===================




|  |  |
| --- | --- |
|  Category  | [Sensors](../../functions#category=Sensors) |
|  Export Size  | 294 B |
|  Last Changed  | 2 months ago |


Reactively track [`window.devicePixelRatio`](https://developer.mozilla.org/ru/docs/Web/API/Window/devicePixelRatio)



> NOTE: there is no event listener for `window.devicePixelRatio` change. So this function uses [`Testing media queries programmatically (window.matchMedia)`](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries) applying the same mechanism as described in [this example](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#monitoring_screen_resolution_or_zoom_level_changes).
> 
> 


Usage
-----




```
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](../../guide/components). 
> 
> 




```
<UseDevicePixelRatio v-slot="{ pixelRatio }">
  Pixel Ratio: {{ pixelRatio }}
</UseDevicePixelRatio>
```


Type Declarations
-----------------




```
/**
 * Reactively track `window.devicePixelRatio`.
 *
 * @see https://vueuse.org/useDevicePixelRatio
 * @param options
 */
export declare function useDevicePixelRatio({ window }?: ConfigurableWindow): {
  pixelRatio: Ref<number>
}
export type UseDevicePixelRatioReturn = ReturnType<typeof useDevicePixelRatio>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useDevicePixelRatio/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useDevicePixelRatio/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useDevicePixelRatio/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useDevicePixelRatio/>

useObjectUrl
============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 278 B |
|  Last Changed  | 2 weeks ago |


Reactive URL representing an object.


Creates an URL for the provided `File`, `Blob`, or `MediaSource` via [URL.createObjectURL()](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) and automatically releases the URL via [URL.revokeObjectURL()](https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL) when the source changes or the component is unmounted.


Usage
-----




```
<script setup>
import { useObjectUrl } from '@vueuse/core'
import { shallowRef } from 'vue'

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

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

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

  <a :href="url">Open file</a>
</template>
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
/**
 * Reactive URL representing an object.
 *
 * @see https://vueuse.org/useObjectUrl
 * @param object
 */
export declare function useObjectUrl(
  object: MaybeRef<Blob | MediaSource | undefined>
): Readonly<Ref<string | undefined>>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useObjectUrl/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useObjectUrl/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useObjectUrl/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useObjectUrl/>

useSorted
=========




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 366 B |
|  Last Changed  | 2 weeks ago |


reactive sort array


Usage
-----




```
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.




```
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
```


Type Declarations
-----------------




```
export type UseSortedCompareFn<T = any> = (a: T, b: T) => number
export type UseSortedFn<T = any> = (
  arr: T[],
  compareFn: UseSortedCompareFn<T>
) => T[]
export interface UseSortedOptions<T = any> {
  /**
   * sort algorithm
   */
  sortFn?: UseSortedFn<T>
  /**
   * compare function
   */
  compareFn?: UseSortedCompareFn<T>
  /**
   * change the value of the source array
   * @default false
   */
  dirty?: boolean
}
export declare function useSorted<T = any>(
  source: MaybeRef<T[]>,
  compareFn?: UseSortedCompareFn<T>
): Ref<T[]>
export declare function useSorted<T = any>(
  source: MaybeRef<T[]>,
  options?: UseSortedOptions<T>
): Ref<T[]>
export declare function useSorted<T = any>(
  source: MaybeRef<T[]>,
  compareFn?: UseSortedCompareFn<T>,
  options?: Omit<UseSortedOptions<T>, "compareFn">
): Ref<T[]>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useSorted/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useSorted/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useSorted/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useSorted/>

useEventBus
===========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 332 B |
|  Last Changed  | 2 months ago |


A basic event bus.


Usage
-----




```
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`](https://antfu.me/notes#typed-provide-and-inject-in-vue) util.




```
// fooKey.ts
import type { EventBusKey } from '@vueuse/core'

export const fooKey: EventBusKey<{ name: foo }> = Symbol('symbol-key')
```




```
import { useEventBus } from '@vueuse/core'

import { fooKey } from './fooKey'

const bus = useEventBus(fooKey)

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


Type Declarations
-----------------



Show Type Declarations

```
export type EventBusListener<T = unknown, P = any> = (
  event: T,
  payload?: P
) => void
export type EventBusEvents<T, P = any> = Set<EventBusListener<T, P>>
export interface EventBusKey<T> extends Symbol {}
export type EventBusIdentifier<T = unknown> = EventBusKey<T> | string | number
export interface UseEventBusReturn<T, P> {
  /**
   * Subscribe to an event. When calling emit, the listeners will execute.
   * @param listener watch listener.
   * @returns a stop function to remove the current callback.
   */
  on: (listener: EventBusListener<T, P>) => Fn
  /**
   * Similar to `on`, but only fires once
   * @param listener watch listener.
   * @returns a stop function to remove the current callback.
   */
  once: (listener: EventBusListener<T, P>) => Fn
  /**
   * Emit an event, the corresponding event listeners will execute.
   * @param event data sent.
   */
  emit: (event?: T, payload?: P) => void
  /**
   * Remove the corresponding listener.
   * @param listener watch listener.
   */
  off: (listener: EventBusListener<T>) => void
  /**
   * Clear all events
   */
  reset: () => void
}
export declare function useEventBus<T = unknown, P = any>(
  key: EventBusIdentifier<T>
): UseEventBusReturn<T, P>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useEventBus/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useEventBus/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useEventBus/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useEventBus/>

useWebWorker
============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 322 B |
|  Last Changed  | last week |
|  Related  | [`useWebWorkerFn`](../usewebworkerfn/index) |


Simple [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) registration and communication.


Usage
-----




```
import { useWebWorker } from '@vueuse/core'

const { data, post, terminate, worker } = useWebWorker('/path/to/worker.js')
```




| State | Type | Description |
| --- | --- | --- |
| data | `Ref<any>` | Reference to the latest data received via the worker, can be watched to respond to incoming messages |
| worker | `ShallowRef<Worker | undefined>` | Reference to the instance of the WebWorker |




| Method | Signature | Description |
| --- | --- | --- |
| post | `(data: any) => void` | Sends data to the worker thread. |
| terminate | `() => void` | Stops and terminates the worker. |


Type Declarations
-----------------




```
export interface UseWebWorkerReturn<Data = any> {
  data: Ref<Data>
  post: (typeof Worker.prototype)["postMessage"]
  terminate: () => void
  worker: ShallowRef<Worker | undefined>
}
type WorkerFn = (...args: unknown[]) => Worker
/**
 * Simple Web Workers registration and communication.
 *
 * @see https://vueuse.org/useWebWorker
 * @param url
 * @param workerOptions
 * @param options
 */
export declare function useWebWorker<T = any>(
  url: string,
  workerOptions?: WorkerOptions,
  options?: ConfigurableWindow
): UseWebWorkerReturn<T>
/**
 * Simple Web Workers registration and communication.
 *
 * @see https://vueuse.org/useWebWorker
 * @param worker
 */
export declare function useWebWorker<T = any>(
  worker: Worker | WorkerFn
): UseWebWorkerReturn<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebWorker/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useWebWorker/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useWebWorker/>

useEyeDropper
=============




|  |  |
| --- | --- |
|  Category  | [Browser](../../functions#category=Browser) |
|  Export Size  | 314 B |
|  Last Changed  | 9 months ago |


Reactive [EyeDropper API](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API)


Usage
-----




```
import { useEyeDropper } from '@vueuse/core'

const { isSupported, open, sRGBHex } = useEyeDropper()
```


Component Usage
---------------



>  This function also provides a renderless component version via the `@vueuse/components` package. [Learn more about the usage](../../guide/components). 
> 
> 




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


Type Declarations
-----------------




```
export interface EyeDropperOpenOptions {
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
   */
  signal?: AbortSignal
}
export interface EyeDropper {
  new (): EyeDropper
  open: (options?: EyeDropperOpenOptions) => Promise<{
    sRGBHex: string
  }>
  [Symbol.toStringTag]: "EyeDropper"
}
export interface UseEyeDropperOptions {
  /**
   * Initial sRGBHex.
   *
   * @default ''
   */
  initialValue?: string
}
/**
 * Reactive [EyeDropper API](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API)
 *
 * @see https://vueuse.org/useEyeDropper
 * @param initialValue string
 */
export declare function useEyeDropper(options?: UseEyeDropperOptions): {
  isSupported: ComputedRef<boolean>
  sRGBHex: Ref<string>
  open: (openOptions?: EyeDropperOpenOptions) => Promise<
    | {
        sRGBHex: string
      }
    | undefined
  >
}
export type UseEyeDropperReturn = ReturnType<typeof useEyeDropper>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useEyeDropper/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useEyeDropper/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useEyeDropper/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useEyeDropper/>

templateRef
===========




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 270 B |
|  Last Changed  | 7 months ago |


Shorthand for binding ref to template element.


Usage
-----




```
<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




```
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`.




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

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

<template>
  <div ref="target" />
</template>
```


Type Declarations
-----------------




```
/**
 * Shorthand for binding ref to template element.
 *
 * @see https://vueuse.org/templateRef
 * @param key
 * @param initialValue
 */
export declare function templateRef<
  T extends HTMLElement | SVGElement | Component | null
>(key: string, initialValue?: T | null): Readonly<Ref<T>>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/templateRef/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/templateRef/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/templateRef/>

computedInject
==============




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 183 B |
|  Last Changed  | 8 months ago |


Combine computed and inject


Usage
-----


In Provider Component




```
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




```
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
})
```


Type Declarations
-----------------



Show Type Declarations

```
export type ComputedInjectGetter<T, K> = (source: T | undefined, ctx?: any) => K
export type ComputedInjectGetterWithDefault<T, K> = (source: T, ctx?: any) => K
export type ComputedInjectSetter<T> = (v: T) => void
export interface WritableComputedInjectOptions<T, K> {
  get: ComputedInjectGetter<T, K>
  set: ComputedInjectSetter<K>
}
export interface WritableComputedInjectOptionsWithDefault<T, K> {
  get: ComputedInjectGetterWithDefault<T, K>
  set: ComputedInjectSetter<K>
}
export declare function computedInject<T, K = any>(
  key: InjectionKey<T> | string,
  getter: ComputedInjectGetter<T, K>
): ComputedRef<K | undefined>
export declare function computedInject<T, K = any>(
  key: InjectionKey<T> | string,
  options: WritableComputedInjectOptions<T, K>
): ComputedRef<K | undefined>
export declare function computedInject<T, K = any>(
  key: InjectionKey<T> | string,
  getter: ComputedInjectGetterWithDefault<T, K>,
  defaultSource: T,
  treatDefaultAsFactory?: false
): ComputedRef<K>
export declare function computedInject<T, K = any>(
  key: InjectionKey<T> | string,
  options: WritableComputedInjectOptionsWithDefault<T, K>,
  defaultSource: T | (() => T),
  treatDefaultAsFactory: true
): ComputedRef<K>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/computedInject/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/computedInject/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/computedInject/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/computedInject/>

useCurrentElement
=================




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 355 B |
|  Last Changed  | 8 months ago |


Get the DOM element of current component as a ref.


Usage
-----




```
import { useCurrentElement } from '@vueuse/core'

const el = useCurrentElement() // ComputedRef<Element>
```


Caveats
-------


This functions uses [`$el` under the hood](https://vuejs.org/api/component-instance.html#el).


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**.


Type Declarations
-----------------




```
export declare function useCurrentElement<
  T extends Element = Element
>(): ComputedRefWithControl<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useCurrentElement/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useCurrentElement/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useCurrentElement/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useCurrentElement/>

usePrevious
===========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 260 B |
|  Last Changed  | 2 weeks ago |


Holds the previous value of a ref.


Usage
-----




```
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
```


Type Declarations
-----------------




```
/**
 * Holds the previous value of a ref.
 *
 * @see   {@link https://vueuse.org/usePrevious}
 */
export declare function usePrevious<T>(
  value: MaybeRefOrGetter<T>
): Readonly<Ref<T | undefined>>
export declare function usePrevious<T>(
  value: MaybeRefOrGetter<T>,
  initialValue: T
): Readonly<Ref<T>>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/usePrevious/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/usePrevious/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/usePrevious/>

useSupported
============




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 194 B |
|  Last Changed  | 4 weeks ago |


SSR compatibility `isSupported`


Usage
-----




```
import { useSupported } from '@vueuse/core'

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

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


Type Declarations
-----------------




```
export declare function useSupported(
  callback: () => unknown
): ComputedRef<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useSupported/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useSupported/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useSupported/>

useTemplateRefsList
===================




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 177 B |
|  Last Changed  | last year |


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



**WARNING**This function only works for Vue 3



Usage
-----




```
<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>
```


Type Declarations
-----------------




```
export type TemplateRefsList<T> = T[] & {
  set(el: Object | null): void
}
export declare function useTemplateRefsList<T = Element>(): Readonly<
  Ref<Readonly<TemplateRefsList<T>>>
>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useTemplateRefsList/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useTemplateRefsList/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useTemplateRefsList/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useTemplateRefsList/>

unrefElement
============




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 165 B |
|  Last Changed  | 2 weeks ago |


Unref for dom element.


Usage
-----




```
<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 bind to the <div> element
const hello = ref() // will be bind to the HelloWorld Component

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


Type Declarations
-----------------




```
export type VueInstance = ComponentPublicInstance
export type MaybeElementRef<T extends MaybeElement = MaybeElement> = MaybeRef<T>
export type MaybeComputedElementRef<T extends MaybeElement = MaybeElement> =
  MaybeRefOrGetter<T>
export type MaybeElement =
  | HTMLElement
  | SVGElement
  | VueInstance
  | undefined
  | null
export type UnRefElementReturn<T extends MaybeElement = MaybeElement> =
  T extends VueInstance ? Exclude<MaybeElement, VueInstance> : T | undefined
/**
 * Get the dom element of a ref of element or Vue component instance
 *
 * @param elRef
 */
export declare function unrefElement<T extends MaybeElement>(
  elRef: MaybeComputedElementRef<T>
): UnRefElementReturn<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/unrefElement/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/unrefElement/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/unrefElement/>

useMounted
==========




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 156 B |
|  Last Changed  | 4 weeks ago |


Mounted state in ref.


Usage
-----




```
import { useMounted } from '@vueuse/core'

const isMounted = useMounted()
```


Which is essentially a shorthand of:




```
const isMounted = ref(false)

onMounted(() => {
  isMounted.value = true
})
```


Type Declarations
-----------------




```
/**
 * Mounted state in ref.
 *
 * @see https://vueuse.org/useMounted
 * @param options
 */
export declare function useMounted(): Ref<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useMounted/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useMounted/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useMounted/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useMounted/>

useClamp
========




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 214 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | last week |


Reactively clamp a value between two other values.


Usage
-----




```
import { useClamp } from '@vueuse/math'

const min = ref(0)
const max = ref(10)
const value = useClamp(0, min, max)
```


You can also pass a `ref` and the returned `computed` will be updated when the source ref changes:




```
import { useClamp } from '@vueuse/math'

const number = ref(0)
const clamped = useClamp(number, 0, 10)
```


Type Declarations
-----------------




```
export declare function useClamp(
  value: ReadonlyRefOrGetter<number>,
  min: MaybeRefOrGetter<number>,
  max: MaybeRefOrGetter<number>
): ComputedRef<number>
export declare function useClamp(
  value: MaybeRefOrGetter<number>,
  min: MaybeRefOrGetter<number>,
  max: MaybeRefOrGetter<number>
): Ref<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useClamp/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/math/useClamp/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useClamp/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useClamp/>

useCached
=========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 169 B |
|  Last Changed  | last year |


Cache a ref with a custom comparator.


Usage
-----




```
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 }
```


Type Declarations
-----------------




```
export declare function useCached<T>(
  refValue: Ref<T>,
  comparator?: (a: T, b: T) => boolean,
  watchOptions?: WatchOptions
): Ref<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/useCached/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/core/useCached/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/useCached/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/useCached/>

createUnrefFn
=============




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 166 B |
|  Last Changed  | 2 weeks ago |
|  Related  | [`reactify`](../../shared/reactify/index) |


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
-----




```
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 */
```


Type Declarations
-----------------




```
export type UnrefFn<T> = T extends (...args: infer A) => infer R
  ? (
      ...args: {
        [K in keyof A]: MaybeRef<A[K]>
      }
    ) => R
  : never
/**
 * Make a plain function accepting ref and raw values as arguments.
 * Returns the same value the unconverted function returns, with proper typing.
 */
export declare function createUnrefFn<T extends Function>(fn: T): UnrefFn<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/createUnrefFn/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/createUnrefFn/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/createUnrefFn/>

useMath
=======




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 198 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 9 months ago |


Reactive `Math` methods.


Usage
-----




```
import { useMath } from '@vueuse/math'

const base = ref(2)
const exponent = ref(3)
const result = useMath('pow', base, exponent) // Ref<8>

const num = ref(2)
const root = useMath('sqrt', num) // Ref<1.4142135623730951>

num.value = 4
console.log(root.value) // 2
```


Type Declarations
-----------------




```
export type UseMathKeys = keyof {
  [K in keyof Math as Math[K] extends (...args: any) => any
    ? K
    : never]: unknown
}
/**
 * Reactive `Math` methods.
 *
 * @see https://vueuse.org/useMath
 */
export declare function useMath<K extends keyof Math>(
  key: K,
  ...args: ArgumentsType<Reactified<Math[K], true>>
): ReturnType<Reactified<Math[K], true>>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useMath/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useMath/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useMath/>

useProjection
=============




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 196 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |
|  Related  | [`createGenericProjection`](../creategenericprojection/index)[`createProjection`](../createprojection/index) |


Reactive numeric projection from one domain to another.


Usage
-----




```
import { useProjection } from '@vueuse/math'

const input = ref(0)
const projected = useProjection(input, [0, 10], [0, 100])

input.value = 5 // projected.value === 50
input.value = 10 // projected.value === 100
```


Type Declarations
-----------------




```
/**
 * Reactive numeric projection from one domain to another.
 *
 * @see https://vueuse.org/useProjection
 */
export declare function useProjection(
  input: MaybeRefOrGetter<number>,
  fromDomain: MaybeRefOrGetter<readonly [number, number]>,
  toDomain: MaybeRefOrGetter<readonly [number, number]>,
  projector?: ProjectorFunction<number, number>
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useProjection/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/math/useProjection/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useProjection/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useProjection/>

useAverage
==========




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 195 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Get the average of an array reactively.


Usage
-----




```
import { useAverage } from '@vueuse/math'

const list = ref([1, 2, 3])
const averageValue = useAverage(list) // Ref<2>
```




```
import { useAverage } from '@vueuse/math'

const a = ref(1)
const b = ref(3)

const averageValue = useAverage(a, b) // Ref<2>
```


Type Declarations
-----------------




```
export declare function useAverage(
  array: MaybeRefOrGetter<MaybeRefOrGetter<number>[]>
): ComputedRef<number>
export declare function useAverage(
  ...args: MaybeRefOrGetter<number>[]
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useAverage/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useAverage/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useAverage/>

useSum
======




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 194 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Get the sum of an array reactively


Usage
-----




```
import { useSum } from '@vueuse/math'

const array = ref([1, 2, 3, 4])
const sum = useSum(array) // Ref<10>
```




```
import { useSum } from '@vueuse/math'

const a = ref(1)
const b = ref(3)

const sum = useSum(a, b, 2) // Ref<6>
```


Type Declarations
-----------------




```
export declare function useSum(
  array: MaybeRefOrGetter<MaybeRefOrGetter<number>[]>
): ComputedRef<number>
export declare function useSum(
  ...args: MaybeRefOrGetter<number>[]
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useSum/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useSum/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useSum/>

createProjection
================




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 193 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |
|  Related  | [`createGenericProjection`](../creategenericprojection/index)[`useProjection`](../useprojection/index) |


Reactive numeric projection from one domain to another.


Usage
-----




```
import { createProjection } from '@vueuse/math'

const useProjector = createProjection([0, 10], [0, 100])
const input = ref(0)
const projected = useProjector(input) // projected.value === 0

input.value = 5 // projected.value === 50
input.value = 10 // projected.value === 100
```


Type Declarations
-----------------




```
export declare function createProjection(
  fromDomain: MaybeRefOrGetter<readonly [number, number]>,
  toDomain: MaybeRefOrGetter<readonly [number, number]>,
  projector?: ProjectorFunction<number, number>
): UseProjection<number, number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/createProjection/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/createProjection/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/createProjection/>

usePrecision
============




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 175 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Reactively set the precision of a number.


Usage
-----




```
import { usePrecision } from '@vueuse/math'

const value = ref(3.1415)
const result = usePrecision(value, 2) // 3.14

const ceilResult = usePrecision(value, 2, {
  math: 'ceil'
}) // 3.15

const floorResult = usePrecision(value, 3, {
  math: 'floor'
}) // 3.141
```


Type Declarations
-----------------




```
export interface UsePrecisionOptions {
  /**
   * Method to use for rounding
   *
   * @default 'round'
   */
  math?: "floor" | "ceil" | "round"
}
/**
 * Reactively set the precision of a number.
 *
 * @see https://vueuse.org/usePrecision
 */
export declare function usePrecision(
  value: MaybeRefOrGetter<number>,
  digits: MaybeRefOrGetter<number>,
  options?: MaybeRefOrGetter<UsePrecisionOptions>
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/usePrecision/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/usePrecision/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/usePrecision/>

useMax
======




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 190 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Reactive `Math.max`.


Usage
-----




```
import { useMax } from '@vueuse/math'

const array = ref([1, 2, 3, 4])
const sum = useMax(array) // Ref<4>
```




```
import { useMax } from '@vueuse/math'

const a = ref(1)
const b = ref(3)

const sum = useMax(a, b, 2) // Ref<3>
```


Type Declarations
-----------------




```
export declare function useMax(
  array: MaybeRefOrGetter<MaybeRefOrGetter<number>[]>
): ComputedRef<number>
export declare function useMax(
  ...args: MaybeRefOrGetter<number>[]
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useMax/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useMax/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useMax/>

logicAnd
========




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 123 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |
|  Alias  | `and` |
|  Related  | [`logicNot`](../logicnot/index)[`logicOr`](../logicor/index) |


`AND` condition for refs.


Usage
-----




```
import { logicAnd } from '@vueuse/math'
import { whenever } from '@vueuse/core'

const a = ref(true)
const b = ref(false)

whenever(logicAnd(a, b), () => {
  console.log('both a and b are now truthy!')
})
```


Type Declarations
-----------------




```
/**
 * `AND` conditions for refs.
 *
 * @see https://vueuse.org/logicAnd
 */
export declare function logicAnd(
  ...args: MaybeRefOrGetter<any>[]
): ComputedRef<boolean>
export { logicAnd as and }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/logicAnd/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/logicAnd/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/logicAnd/>

logicOr
=======




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 122 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |
|  Alias  | `or` |
|  Related  | [`logicAnd`](../logicand/index)[`logicNot`](../logicnot/index) |


`OR` conditions for refs.


Usage
-----




```
import { logicOr } from '@vueuse/math'
import { whenever } from '@vueuse/core'

const a = ref(true)
const b = ref(false)

whenever(logicOr(a, b), () => {
  console.log('either a or b is truthy!')
})
```


Type Declarations
-----------------




```
/**
 * `OR` conditions for refs.
 *
 * @see https://vueuse.org/logicOr
 */
export declare function logicOr(
  ...args: MaybeRefOrGetter<any>[]
): ComputedRef<boolean>
export { logicOr as or }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/logicOr/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/logicOr/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/logicOr/>

useMin
======




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 191 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Reactive `Math.min`.


Usage
-----




```
import { useMin } from '@vueuse/math'

const array = ref([1, 2, 3, 4])
const sum = useMin(array) // Ref<1>
```




```
import { useMin } from '@vueuse/math'

const a = ref(1)
const b = ref(3)

const sum = useMin(a, b, 2) // Ref<1>
```


Type Declarations
-----------------




```
export declare function useMin(
  array: MaybeRefOrGetter<MaybeRefOrGetter<number>[]>
): ComputedRef<number>
export declare function useMin(
  ...args: MaybeRefOrGetter<number>[]
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useMin/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useMin/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useMin/>

useRound
========




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 115 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Reactive `Math.round`.


Usage
-----




```
import { useRound } from '@vueuse/math'

const value = ref(20.49)
const result = useRound(value) // 20
```


Type Declarations
-----------------




```
/**
 * Reactive `Math.round`.
 *
 * @see https://vueuse.org/useRound
 */
export declare function useRound(
  value: MaybeRefOrGetter<number>
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useRound/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useRound/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useRound/>

createGenericProjection
=======================




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 132 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |
|  Related  | [`createProjection`](../createprojection/index)[`useProjection`](../useprojection/index) |


Generic version of [`createProjection`](../createprojection/index) Accepts a custom projector function to map arbitrary type of domains.


Refer to [`createProjection`](../createprojection/index) and `useProjection`


Type Declarations
-----------------




```
export type ProjectorFunction<F, T> = (
  input: F,
  from: readonly [F, F],
  to: readonly [T, T]
) => T
export type UseProjection<F, T> = (input: MaybeRefOrGetter<F>) => ComputedRef<T>
export declare function createGenericProjection<F = number, T = number>(
  fromDomain: MaybeRefOrGetter<readonly [F, F]>,
  toDomain: MaybeRefOrGetter<readonly [T, T]>,
  projector: ProjectorFunction<F, T>
): UseProjection<F, T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/createGenericProjection/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/createGenericProjection/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/createGenericProjection/>

useTrunc
========




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 120 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Reactive `Math.trunc`.


Usage
-----




```
import { useTrunc } from '@vueuse/math'

const value1 = ref(0.95)
const value2 = ref(-2.34)
const result1 = useTrunc(value1) // 0
const result2 = useTrunc(value2) // -2
```


Type Declarations
-----------------




```
/**
 * Reactive `Math.trunc`.
 *
 * @see https://vueuse.org/useTrunc
 */
export declare function useTrunc(
  value: MaybeRefOrGetter<number>
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useTrunc/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useTrunc/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useTrunc/>

useAbs
======




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 115 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Reactive `Math.abs`.


Usage
-----




```
import { useAbs } from '@vueuse/math'

const value = ref(-23)
const absValue = useAbs(value) // Ref<23>
```


Type Declarations
-----------------




```
/**
 * Reactive `Math.abs`.
 *
 * @see https://vueuse.org/useAbs
 */
export declare function useAbs(
  value: MaybeRefOrGetter<number>
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useAbs/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useAbs/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useAbs/>

useCeil
=======




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 115 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Reactive `Math.ceil`


Usage
-----




```
import { useCeil } from '@vueuse/math'

const value = ref(0.95)
const result = useCeil(value) // 1
```


Type Declarations
-----------------




```
/**
 * Reactive `Math.ceil`.
 *
 * @see https://vueuse.org/useCeil
 */
export declare function useCeil(
  value: MaybeRefOrGetter<number>
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useCeil/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useCeil/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useCeil/>

useFloor
========




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 114 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |


Reactive `Math.floor`.


Usage
-----




```
import { useFloor } from '@vueuse/math'

const value = ref(45.95)
const result = useFloor(value) // 45
```


Type Declarations
-----------------




```
/**
 * Reactive `Math.floor`
 *
 * @see https://vueuse.org/useFloor
 */
export declare function useFloor(
  value: MaybeRefOrGetter<number>
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/useFloor/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/useFloor/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/useFloor/>

useRouteQuery
=============




|  |  |
| --- | --- |
|  Category  | [@Router](../../functions#category=%40Router) |
|  Export Size  | 506 B |
|  Package  | `@vueuse/router` |
|  Last Changed  | 2 weeks ago |


Shorthand for a reactive `route.query`. Available in the [@vueuse/router](../readme) add-on.


Usage
-----




```
import { useRouteQuery } from '@vueuse/router'

const search = useRouteQuery('search')

const search = useRouteQuery('search', 'foo') // or with a default value

const page = useRouteQuery('page', '1', { transform: Number }) // or transforming value

console.log(search.value) // route.query.search
search.value = 'foobar' // router.replace({ query: { search: 'foobar' } })
```


Type Declarations
-----------------




```
export declare function useRouteQuery(
  name: string
): Ref<null | string | string[]>
export declare function useRouteQuery<
  T extends RouterQueryValue = RouterQueryValue,
  K = T
>(
  name: string,
  defaultValue?: T,
  options?: ReactiveRouteOptionsWithTransform<T, K>
): Ref<K>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/router/useRouteQuery/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/router/useRouteQuery/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/router/useRouteQuery/>

logicNot
========




|  |  |
| --- | --- |
|  Category  | [@Math](../../functions#category=%40Math) |
|  Export Size  | 109 B |
|  Package  | `@vueuse/math` |
|  Last Changed  | 2 weeks ago |
|  Alias  | `not` |
|  Related  | [`logicAnd`](../logicand/index)[`logicOr`](../logicor/index) |


`NOT` condition for ref.


Usage
-----




```
import { logicNot } from '@vueuse/math'
import { whenever } from '@vueuse/core'

const a = ref(true)

whenever(logicNot(a), () => {
  console.log('a is now falsy!')
})
```


Type Declarations
-----------------




```
/**
 * `NOT` conditions for refs.
 *
 * @see https://vueuse.org/logicNot
 */
export declare function logicNot(v: MaybeRefOrGetter<any>): ComputedRef<boolean>
export { logicNot as not }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/math/logicNot/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/math/logicNot/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/math/logicNot/>

useRouteParams
==============




|  |  |
| --- | --- |
|  Category  | [@Router](../../functions#category=%40Router) |
|  Export Size  | 473 B |
|  Package  | `@vueuse/router` |
|  Last Changed  | 2 weeks ago |


Shorthand for a reactive `route.params`. Available in the [@vueuse/router](../readme) add-on.


Usage
-----




```
import { useRouteParams } from '@vueuse/router'

const userId = useRouteParams('userId')

const userId = useRouteParams('userId', '-1') // or with a default value

const userId = useRouteParams('page', '1', { transform: Number }) // or transforming value

console.log(userId.value) // route.params.userId
userId.value = '100' // router.replace({ params: { userId: '100' } })
```


Type Declarations
-----------------




```
export declare function useRouteParams(
  name: string
): Ref<null | string | string[]>
export declare function useRouteParams<
  T extends RouterQueryValue = RouterQueryValue,
  K = T
>(
  name: string,
  defaultValue?: T,
  options?: ReactiveRouteOptionsWithTransform<T, K>
): Ref<K>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/router/useRouteParams/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/router/useRouteParams/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/router/useRouteParams/>

useRouteHash
============




|  |  |
| --- | --- |
|  Category  | [@Router](../../functions#category=%40Router) |
|  Export Size  | 442 B |
|  Package  | `@vueuse/router` |
|  Last Changed  | 2 weeks ago |


Shorthand for a reactive `route.hash`. Available in the [@vueuse/router](../readme) add-on.


Usage
-----




```
import { useRouteHash } from '@vueuse/router'

const search = useRouteHash()

console.log(search.value) // route.hash
search.value = 'foobar' // router.replace({ hash: 'foobar' })
```


Type Declarations
-----------------




```
export declare function useRouteHash(
  defaultValue?: string,
  { mode, route, router }?: ReactiveRouteOptions
): WritableComputedRef<string>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/router/useRouteHash/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/router/useRouteHash/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/router/useRouteHash/>

useAxios
========




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 1.54 kB |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | last week |


Wrapper for [`axios`](https://github.com/axios/axios).

 Available in the [@vueuse/integrations](../readme) add-on. Install
-------




```
npm i axios
```


Usage
-----




```
import { useAxios } from '@vueuse/integrations/useAxios'

const { data, isFinished } = useAxios('/api/posts')
```


or use an instance of axios




```
import axios from 'axios'
import { useAxios } from '@vueuse/integrations/useAxios'

const instance = axios.create({
  baseURL: '/api',
})

const { data, isFinished } = useAxios('/posts', instance)
```


use an instance of axios with config options




```
import axios from 'axios'
import { useAxios } from '@vueuse/integrations/useAxios'

const instance = axios.create({
  baseURL: '/api',
})

const { data, isFinished } = useAxios('/posts', { method: 'POST' }, instance)
```


When you don't pass the `url`. The default value is `{immediate: false}`




```
import { useAxios } from '@vueuse/integrations/useAxios'

const { execute } = useAxios()
execute(url)
```


The `execute` function `url` here is optional, and `url2` will replace the `url1`.




```
import { useAxios } from '@vueuse/integrations/useAxios'

const { execute } = useAxios(url1, {}, { immediate: false })
execute(url2)
```


The `execute` function can accept `config` only.




```
import { useAxios } from '@vueuse/integrations/useAxios'

const { execute } = useAxios(url1, { method: 'GET' }, { immediate: false })
execute({ params: { key: 1 } })
execute({ params: { key: 2 } })
```


The `execute` function resolves with a result of network request.




```
import { useAxios } from '@vueuse/integrations/useAxios'

const { execute } = useAxios()
const result = await execute(url)
```


use an instance of axios with `immediate` options




```
import axios from 'axios'
import { useAxios } from '@vueuse/integrations/useAxios'

const instance = axios.create({
  baseURL: '/api',
})

const { data, isFinished } = useAxios('/posts', { method: 'POST' }, instance, {
  immediate: false,
})
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseAxiosReturn<T, R = AxiosResponse<T>, _D = any> {
  /**
   * Axios Response
   */
  response: ShallowRef<R | undefined>
  /**
   * Axios response data
   */
  data: Ref<T | undefined>
  /**
   * Indicates if the request has finished
   */
  isFinished: Ref<boolean>
  /**
   * Indicates if the request is currently loading
   */
  isLoading: Ref<boolean>
  /**
   * Indicates if the request was canceled
   */
  isAborted: Ref<boolean>
  /**
   * Any errors that may have occurred
   */
  error: ShallowRef<unknown | undefined>
  /**
   * Aborts the current request
   */
  abort: (message?: string | undefined) => void
  /**
   * Alias to `abort`
   */
  cancel: (message?: string | undefined) => void
  /**
   * Alice to `isAborted`
   */
  isCanceled: Ref<boolean>
}
export interface StrictUseAxiosReturn<T, R, D> extends UseAxiosReturn<T, R, D> {
  /**
   * Manually call the axios request
   */
  execute: (
    url?: string | AxiosRequestConfig<D>,
    config?: AxiosRequestConfig<D>
  ) => Promise<StrictUseAxiosReturn<T, R, D>>
}
export interface EasyUseAxiosReturn<T, R, D> extends UseAxiosReturn<T, R, D> {
  /**
   * Manually call the axios request
   */
  execute: (
    url: string,
    config?: AxiosRequestConfig<D>
  ) => Promise<EasyUseAxiosReturn<T, R, D>>
}
export interface UseAxiosOptions<T = any> {
  /**
   * Will automatically run axios request when `useAxios` is used
   *
   */
  immediate?: boolean
  /**
   * Use shallowRef.
   *
   * @default true
   */
  shallow?: boolean
  /**
   * Callback when error is caught.
   */
  onError?: (e: unknown) => void
  /**
   * Callback when success is caught.
   */
  onSuccess?: (data: T) => void
  /**
   * Initial data to use
   */
  initialData?: T
  /**
   * Sets the state to initialState before executing the promise.
   */
  resetOnExecute?: boolean
  /**
   * Callback when request is finished.
   */
  onFinish?: () => void
}
export declare function useAxios<T = any, R = AxiosResponse<T>, D = any>(
  url: string,
  config?: AxiosRequestConfig<D>,
  options?: UseAxiosOptions
): StrictUseAxiosReturn<T, R, D> & Promise<StrictUseAxiosReturn<T, R, D>>
export declare function useAxios<T = any, R = AxiosResponse<T>, D = any>(
  url: string,
  instance?: AxiosInstance,
  options?: UseAxiosOptions
): StrictUseAxiosReturn<T, R, D> & Promise<StrictUseAxiosReturn<T, R, D>>
export declare function useAxios<T = any, R = AxiosResponse<T>, D = any>(
  url: string,
  config: AxiosRequestConfig<D>,
  instance: AxiosInstance,
  options?: UseAxiosOptions
): StrictUseAxiosReturn<T, R, D> & Promise<StrictUseAxiosReturn<T, R, D>>
export declare function useAxios<T = any, R = AxiosResponse<T>, D = any>(
  config?: AxiosRequestConfig<D>
): EasyUseAxiosReturn<T, R, D> & Promise<EasyUseAxiosReturn<T, R, D>>
export declare function useAxios<T = any, R = AxiosResponse<T>, D = any>(
  instance?: AxiosInstance
): EasyUseAxiosReturn<T, R, D> & Promise<EasyUseAxiosReturn<T, R, D>>
export declare function useAxios<T = any, R = AxiosResponse<T>, D = any>(
  config?: AxiosRequestConfig<D>,
  instance?: AxiosInstance
): EasyUseAxiosReturn<T, R, D> & Promise<EasyUseAxiosReturn<T, R, D>>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useAxios/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useAxios/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useAxios/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useAxios/>

useAsyncValidator
=================




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 1.34 kB |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | 2 weeks ago |


Wrapper for [`async-validator`](https://github.com/yiminghe/async-validator).

 Available in the [@vueuse/integrations](../readme) add-on. Install
-------




```
npm i async-validator
```


Usage
-----




```
import { useAsyncValidator } from '@vueuse/integrations/useAsyncValidator'
```


Type Declarations
-----------------



Show Type Declarations

```
export type AsyncValidatorError = Error & {
  errors: ValidateError[]
  fields: Record<string, ValidateError[]>
}
export interface UseAsyncValidatorExecuteReturn {
  pass: boolean
  errors: AsyncValidatorError["errors"] | undefined
  errorInfo: AsyncValidatorError | null
  errorFields: AsyncValidatorError["fields"] | undefined
}
export interface UseAsyncValidatorReturn {
  pass: Ref<boolean>
  isFinished: Ref<boolean>
  errors: Ref<AsyncValidatorError["errors"] | undefined>
  errorInfo: Ref<AsyncValidatorError | null>
  errorFields: Ref<AsyncValidatorError["fields"] | undefined>
  execute: () => Promise<UseAsyncValidatorExecuteReturn>
}
export interface UseAsyncValidatorOptions {
  /**
   * @see https://github.com/yiminghe/async-validator#options
   */
  validateOption?: ValidateOption
  /**
   * The validation will be triggered right away for the first time.
   * Only works when `manual` is not set to true.
   *
   * @default true
   */
  immediate?: boolean
  /**
   * If set to true, the validation will not be triggered automatically.
   */
  manual?: boolean
}
/**
 * Wrapper for async-validator.
 *
 * @see https://vueuse.org/useAsyncValidator
 * @see https://github.com/yiminghe/async-validator
 */
export declare function useAsyncValidator(
  value: MaybeRefOrGetter<Record<string, any>>,
  rules: MaybeRefOrGetter<Rules>,
  options?: UseAsyncValidatorOptions
): UseAsyncValidatorReturn & PromiseLike<UseAsyncValidatorReturn>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useAsyncValidator/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useAsyncValidator/demo.client.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useAsyncValidator/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useAsyncValidator/>

useDrauu
========




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 924 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | 10 months ago |


Reactive instance for [drauu](https://github.com/antfu/drauu).

 Available in the [@vueuse/integrations](../readme) add-on. Install
-------




```
npm i drauu
```


Usage
-----




```
<script setup>
import { ref } from 'vue'
import { toRefs } from '@vueuse/core'
import { useDrauu } from '@vueuse/integrations/useDrauu'

const target = ref()
const { undo, redo, canUndo, canRedo, brush } = useDrauu(target)
const { color, size } = toRefs(brush)
</script>

<template>
  <svg ref="target"></svg>
</template>
```


Type Declarations
-----------------




```
export type UseDrauuOptions = Omit<Options, "el">
export interface UseDrauuReturn {
  drauuInstance: Ref<Drauu | undefined>
  load: (svg: string) => void
  dump: () => string | undefined
  clear: () => void
  cancel: () => void
  undo: () => boolean | undefined
  redo: () => boolean | undefined
  canUndo: Ref<boolean>
  canRedo: Ref<boolean>
  brush: Ref<Brush>
  onChanged: EventHookOn
  onCommitted: EventHookOn
  onStart: EventHookOn
  onEnd: EventHookOn
  onCanceled: EventHookOn
}
/**
 * Reactive drauu
 *
 * @see https://vueuse.org/useDrauu
 * @param target The target svg element
 * @param options Drauu Options
 */
export declare function useDrauu(
  target: MaybeComputedElementRef,
  options?: UseDrauuOptions
): UseDrauuReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useDrauu/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useDrauu/demo.client.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useDrauu/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useDrauu/>

useCookies
==========




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 691 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | last month |


Wrapper for [`universal-cookie`](https://www.npmjs.com/package/universal-cookie).



**TIP**When using with Nuxt 3, this functions will **NOT** be auto imported in favor of Nuxt's built-in [`useCookie()`](https://v3.nuxtjs.org/api/composables/use-cookie). Use explicit import if you want to use the function from VueUse.



Available in the [@vueuse/integrations](../readme) add-on.


Install
-------




```
npm i universal-cookie
```


Usage
-----


### Common usage




```
<template>
  <div>
    <strong>locale</strong>: {{ cookies.get('locale') }}
    <hr>
    <pre>{{ cookies.getAll() }}</pre>
    <button @click="cookies.set('locale', 'ru-RU')">Russian</button>
    <button @click="cookies.set('locale', 'en-US')">English</button>
  </div>
</template>

<script>
  import { defineComponent } from 'vue'
  import { useCookies } from '@vueuse/integrations/useCookies'

  export default defineComponent({
    setup() {
      const cookies = useCookies(['locale'])
      return {
        cookies,
      }
    },
  })
</script>
```


Options
-------


Access and modify cookies using vue composition-api.



> By default, you should use it inside `setup()`, but this function also works anywhere else.
> 
> 




```
const { get, getAll, set, remove, addChangeListener, removeChangeListener } = useCookies(['cookie-name'], { doNotParse: false, autoUpdateDependencies: false })
```


### 
`dependencies` (optional)


Let you optionally specify a list of cookie names your component depend on or that should trigger a re-render. If unspecified, it will render on every cookie change.


### 
`options` (optional)


* `doNotParse` (boolean = false): do not convert the cookie into an object no matter what. **Passed as default value to [`get`](../../shared/get/index) `getAll` methods.**
* `autoUpdateDependencies` (boolean = false): automatically add cookie names ever provided to [`get`](../../shared/get/index) method. If **true** then you don't need to care about provided `dependencies`.


### 
`cookies` (optional)


Let you provide a `universal-cookie` instance (creates a new instance by default)



> Info about methods available in the [universal-cookie api docs](https://www.npmjs.com/package/universal-cookie#api---cookies-class)
> 
> 



`createCookies([req])`
-----------------------


Create a `universal-cookie` instance using request (default is window.document.cookie) and returns [`useCookies`](index) function with provided universal-cookie instance


* req (object): Node's [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage) request object


Type Declarations
-----------------



Show Type Declarations

```
/// <reference types="node" />
/**
 * Creates a new {@link useCookies} function
 * @param {Object} req - incoming http request (for SSR)
 * @see https://github.com/reactivestack/cookies/tree/master/packages/universal-cookie universal-cookie
 * @description Creates universal-cookie instance using request (default is window.document.cookie) and returns {@link useCookies} function with provided universal-cookie instance
 */
export declare function createCookies(req?: IncomingMessage): (
  dependencies?: string[] | null,
  {
    doNotParse,
    autoUpdateDependencies,
  }?: {
    doNotParse?: boolean | undefined
    autoUpdateDependencies?: boolean | undefined
  }
) => {
  /**
   * Reactive get cookie by name. If **autoUpdateDependencies = true** then it will update watching dependencies
   */
  get: <T = any>(name: string, options?: CookieGetOptions | undefined) => T
  /**
   * Reactive get all cookies
   */
  getAll: <T_1 = any>(options?: CookieGetOptions | undefined) => T_1
  set: (
    name: string,
    value: any,
    options?: CookieSetOptions | undefined
  ) => void
  remove: (name: string, options?: CookieSetOptions | undefined) => void
  addChangeListener: (callback: CookieChangeListener) => void
  removeChangeListener: (callback: CookieChangeListener) => void
}
/**
 * Reactive methods to work with cookies (use {@link createCookies} method instead if you are using SSR)
 * @param {string[]|null|undefined} dependencies - array of watching cookie's names. Pass empty array if don't want to watch cookies changes.
 * @param {Object} options
 * @param {boolean} options.doNotParse - don't try parse value as JSON
 * @param {boolean} options.autoUpdateDependencies - automatically update watching dependencies
 * @param {Object} cookies - universal-cookie instance
 */
export declare function useCookies(
  dependencies?: string[] | null,
  {
    doNotParse,
    autoUpdateDependencies,
  }?: {
    doNotParse?: boolean | undefined
    autoUpdateDependencies?: boolean | undefined
  },
  cookies?: Cookie
): {
  /**
   * Reactive get cookie by name. If **autoUpdateDependencies = true** then it will update watching dependencies
   */
  get: <T = any>(name: string, options?: CookieGetOptions | undefined) => T
  /**
   * Reactive get all cookies
   */
  getAll: <T_1 = any>(options?: CookieGetOptions | undefined) => T_1
  set: (
    name: string,
    value: any,
    options?: CookieSetOptions | undefined
  ) => void
  remove: (name: string, options?: CookieSetOptions | undefined) => void
  addChangeListener: (callback: CookieChangeListener) => void
  removeChangeListener: (callback: CookieChangeListener) => void
}
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useCookies/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useCookies/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useCookies/>

useFocusTrap
============




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 718 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | last year |


Reactive wrapper for [`focus-trap`](https://github.com/focus-trap/focus-trap).


For more information on what options can be passed, see [`createOptions`](https://github.com/focus-trap/focus-trap#createfocustrapelement-createoptions) in the `focus-trap` documentation.

 Available in the [@vueuse/integrations](../readme) add-on. Install
-------




```
npm i focus-trap
```


Usage
-----


**Basic Usage**




```
<script setup>
import { ref } from 'vue'
import { useFocusTrap } from '@vueuse/integrations/useFocusTrap'

const target = ref()
const { hasFocus, activate, deactivate } = useFocusTrap(target)
</script>

<template>
  <div>
    <button @click="activate()">Activate</button>
    <div ref="target">
      <span>Has Focus: {{ hasFocus }}</span>
      <input type="text" />
      <button @click="deactivate()">Deactivate</button>
    </div>
  </div>
</template>
```


**Automatically Focus**




```
<script setup>
import { ref } from 'vue'
import { useFocusTrap } from '@vueuse/integrations/useFocusTrap'

const target = ref()
const { hasFocus, activate, deactivate } = useFocusTrap(target, { immediate: true })
</script>

<template>
  <div>
    <div ref="target">...</div>
  </div>
</template>
```


**Conditional Rendering**


This function can't properly activate focus on elements with conditional rendering using `v-if`. This is because they do not exist in the DOM at the time of the focus activation. To solve this you need to activate on the next tick.




```
<script setup>
import { nextTick, ref } from 'vue'

const target = ref()
const { activate, deactivate } = useFocusTrap(target, { immediate: true })

const show = ref(false)  

const reveal = async () => {
  show.value = true
  
  await nextTick()
  activate()
}
</script>

<template>
  <div>
    <div ref="target" v-if="show">...</div>
    
    <button @click="reveal">Reveal and Focus</button>
  </div>
</template>
```


Using Component
---------------


With the `UseFocusTrap` component, Focus Trap will be activated automatically on mounting this component and deactivated on unmount.




```
<script setup>
import { ref } from 'vue'
import { UseFocusTrap } from '@vueuse/integrations/useFocusTrap/component'

const show = ref(false)
</script>

<template>
  <UseFocusTrap v-if="show" :options="{ immediate: true }">
    <div class="modal">...</div>
  </UseFocusTrap>
</template>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseFocusTrapOptions extends Options {
  /**
   * Immediately activate the trap
   */
  immediate?: boolean
}
export interface UseFocusTrapReturn {
  /**
   * Indicates if the focus trap is currently active
   */
  hasFocus: Ref<boolean>
  /**
   * Indicates if the focus trap is currently paused
   */
  isPaused: Ref<boolean>
  /**
   * Activate the focus trap
   *
   * @see https://github.com/focus-trap/focus-trap#trapactivateactivateoptions
   * @param opts Activate focus trap options
   */
  activate: (opts?: ActivateOptions) => void
  /**
   * Deactivate the focus trap
   *
   * @see https://github.com/focus-trap/focus-trap#trapdeactivatedeactivateoptions
   * @param opts Deactivate focus trap options
   */
  deactivate: (opts?: DeactivateOptions) => void
  /**
   * Pause the focus trap
   *
   * @see https://github.com/focus-trap/focus-trap#trappause
   */
  pause: Fn
  /**
   * Unpauses the focus trap
   *
   * @see https://github.com/focus-trap/focus-trap#trapunpause
   */
  unpause: Fn
}
/**
 * Reactive focus-trap
 *
 * @see https://vueuse.org/useFocusTrap
 * @param target The target element to trap focus within
 * @param options Focus trap options
 * @param autoFocus Focus trap automatically when mounted
 */
export declare function useFocusTrap(
  target: MaybeElementRef,
  options?: UseFocusTrapOptions
): UseFocusTrapReturn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useFocusTrap/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useFocusTrap/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useFocusTrap/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useFocusTrap/>

useSortable
===========




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 692 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | 2 weeks ago |


Wrapper for [`sortable`](https://github.com/SortableJS/Sortable).


For more information on what options can be passed, see [`Sortable.options`](https://github.com/SortableJS/Sortable#options) in the `Sortable` documentation.

 Available in the [@vueuse/integrations](../readme) add-on. Install
-------




```
npm i sortablejs
```


Usage
-----


### Use template ref




```
<script setup lang="ts">
import { useSortable } from '@vueuse/integrations/useSortable'
import { ref } from 'vue'

const el = ref<HTMLElement | null>(null)
const list = ref([{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }])

useSortable(el, list)
</script>

<template>
  <div ref="el">
    <div v-for="item in list" :key="item.id">
      {{ item.name }}
    </div>
  </div>
</template>
```


### Use specifies the selector to operate on




```
<script setup lang="ts">
import { useSortable } from '@vueuse/integrations/useSortable'
import { ref } from 'vue'

const el = ref<HTMLElement | null>(null)
const list = ref([{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }])

useSortable(el, list, {
  handle: '.handle'
})
</script>

<template>
  <div ref="el">
    <div v-for="item in list" :key="item.id">
      <span>{{ item.name }}</span>
      <span class="handle">*</span>
    </div>
  </div>
</template>
```


### Use a selector to get the root element




```
<script setup lang="ts">
import { useSortable } from '@vueuse/integrations/useSortable'
import { ref } from 'vue'

const list = ref([{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }])

useSortable('#dv', list)
</script>

<template>
  <div id="dv">
    <div v-for="item in list" :key="item.id">
      <span>{{ item.name }}</span>
    </div>
  </div>
</template>
```


### Tips


If you want to handle the onUpdate yourself, you can pass in onUpdate parameters, and we also exposed a function to move the item position.




```
import { moveArrayElement } from '@vueuse/integrations/useSortable'

useSortable(el, list, {
  onUpdate: (e) => {
    // do something
    moveArrayElement(list.value, e.oldIndex, e.newIndex)
    // do something
  }
})
```


Type Declarations
-----------------




```
export interface UseSortableReturn {
  /**
   * start sortable instance
   */
  start: () => void
  /**
   * destroy sortable instance
   */
  stop: () => void
}
export type UseSortableOptions = Options & ConfigurableDocument
export declare function useSortable<T>(
  selector: string,
  list: MaybeRefOrGetter<T[]>,
  options?: UseSortableOptions
): UseSortableReturn
export declare function useSortable<T>(
  el: MaybeRefOrGetter<HTMLElement | null | undefined>,
  list: MaybeRefOrGetter<T[]>,
  options?: UseSortableOptions
): UseSortableReturn
export declare function moveArrayElement<T>(
  list: MaybeRefOrGetter<T[]>,
  from: number,
  to: number
): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useSortable/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useSortable/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useSortable/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useSortable/>

useFuse
=======




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 445 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | 2 weeks ago |


Easily implement fuzzy search using a composable with [Fuse.js](https://github.com/krisk/fuse).


From the Fuse.js website:



> 
> What is fuzzy searching?
> 
> 
> Generally speaking, fuzzy searching (more formally known as approximate string matching) is the technique of finding strings that are approximately equal to a given pattern (rather than exactly).
> 
> 
> 

 Available in the [@vueuse/integrations](../readme) add-on. Install Fuse.js as a peer dependency
------------------------------------


### NPM




```
npm install fuse.js
```


### Yarn




```
yarn add fuse.js
```


Usage
-----




```
import { ref } from 'vue'
import { useFuse } from '@vueuse/integrations/useFuse'

const data = [
  'John Smith',
  'John Doe',
  'Jane Doe',
  'Phillip Green',
  'Peter Brown',
]

const input = ref('Jhon D')

const { results } = useFuse(input, data)

/*
 * Results:
 *
 * { "item": "John Doe", "index": 1 }
 * { "item": "John Smith", "index": 0 }
 * { "item": "Jane Doe", "index": 2 }
 *
 */
```


Type Declarations
-----------------




```
export type FuseOptions<T> = Fuse.IFuseOptions<T>
export interface UseFuseOptions<T> {
  fuseOptions?: FuseOptions<T>
  resultLimit?: number
  matchAllWhenSearchEmpty?: boolean
}
export declare function useFuse<DataItem>(
  search: MaybeRefOrGetter<string>,
  data: MaybeRefOrGetter<DataItem[]>,
  options?: MaybeRefOrGetter<UseFuseOptions<DataItem>>
): {
  fuse: Ref<{
    search: <R = DataItem>(
      pattern: string | Fuse.Expression,
      options?: Fuse.FuseSearchOptions | undefined
    ) => Fuse.FuseResult<R>[]
    setCollection: (
      docs: readonly DataItem[],
      index?: Fuse.FuseIndex<DataItem> | undefined
    ) => void
    add: (doc: DataItem) => void
    remove: (predicate: (doc: DataItem, idx: number) => boolean) => DataItem[]
    removeAt: (idx: number) => void
    getIndex: () => Fuse.FuseIndex<DataItem>
  }>
  results: ComputedRef<Fuse.FuseResult<DataItem>[]>
}
export type UseFuseReturn = ReturnType<typeof useFuse>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useFuse/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useFuse/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useFuse/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useFuse/>

useIDBKeyval
============




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 675 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | 2 weeks ago |


Wrapper for [`idb-keyval`](https://www.npmjs.com/package/idb-keyval).

 Available in the [@vueuse/integrations](../readme) add-on. Install idb-keyval as a peer dependency
---------------------------------------




```
npm install idb-keyval
```


Usage
-----




```
import { useIDBKeyval } from '@vueuse/integrations/useIDBKeyval'

// bind object
const { data: storedObject, isFinished } = useIDBKeyval('my-idb-keyval-store', { hello: 'hi', greeting: 'Hello' })

// update object
storedObject.value.hello = 'hola'

// bind boolean
const flag = useIDBKeyval('my-flag', true) // returns Ref<boolean>

// bind number
const count = useIDBKeyval('my-count', 0) // returns Ref<number>

// delete data from idb storage
storedObject.value = null
```


Type Declarations
-----------------




```
export interface UseIDBOptions extends ConfigurableFlush {
  /**
   * Watch for deep changes
   *
   * @default true
   */
  deep?: boolean
  /**
   * On error callback
   *
   * Default log error to `console.error`
   */
  onError?: (error: unknown) => void
  /**
   * Use shallow ref as reference
   *
   * @default false
   */
  shallow?: boolean
  /**
   * Write the default value to the storage when it does not exist
   *
   * @default true
   */
  writeDefaults?: boolean
}
/**
 *
 * @param key
 * @param initialValue
 * @param options
 */
export declare function useIDBKeyval<T>(
  key: IDBValidKey,
  initialValue: MaybeRefOrGetter<T>,
  options?: UseIDBOptions
): {
  data: RemovableRef<T>
  isFinished: Ref<boolean>
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useIDBKeyval/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useIDBKeyval/demo.client.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useIDBKeyval/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useIDBKeyval/>

useNProgress
============




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 425 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | last week |


Reactive wrapper for [`nprogress`](https://github.com/rstacruz/nprogress).

 Available in the [@vueuse/integrations](../readme) add-on. Install
-------




```
npm i nprogress
```


Usage
-----




```
import { useNProgress } from '@vueuse/integrations/useNProgress'

const { isLoading } = useNProgress()

function toggle() {
  isLoading.value = !isLoading.value
}
```


### Passing a progress percentage


You can pass a percentage to indicate where the bar should start from.




```
import { useNProgress } from '@vueuse/integrations/useNProgress'

const { progress } = useNProgress(0.5)

function done() {
  progress.value = 1.0
}
```



> To change the progress percentage, set `progress.value = n`, where n is a number between 0..1.
> 
> 


### Customization


Just edit [nprogress.css](http://ricostacruz.com/nprogress/nprogress.css) to your liking. Tip: you probably only want to find and replace occurrences of #29d.


You can [configure](https://github.com/rstacruz/nprogress#configuration) it by passing an object as a second parameter.




```
import { useNProgress } from '@vueuse/integrations/useNProgress'

useNProgress(null, {
  minimum: 0.1,
  // ...
})
```


Type Declarations
-----------------




```
export type UseNProgressOptions = Partial<NProgressOptions>
/**
 * Reactive progress bar.
 *
 * @see https://vueuse.org/useNProgress
 */
export declare function useNProgress(
  currentProgress?: MaybeRefOrGetter<number | null | undefined>,
  options?: UseNProgressOptions
): {
  isLoading: WritableComputedRef<boolean>
  progress: Ref<number | (() => number | null | undefined) | null | undefined>
  start: () => nprogress.NProgress
  done: (force?: boolean | undefined) => nprogress.NProgress
  remove: () => void
}
export type UseNProgressReturn = ReturnType<typeof useNProgress>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useNProgress/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useNProgress/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useNProgress/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useNProgress/>

useChangeCase
=============




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 385 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | last week |


Reactive wrapper for [`change-case`](https://github.com/blakeembrey/change-case).


Subsitutes `useCamelCase`, `usePascalCase`, `useSnakeCase`, `useSentenceCase`, `useCapitalize`, etc.

 Available in the [@vueuse/integrations](../readme) add-on. Install
-------




```
npm i change-case
```


Usage
-----




```
import { useChangeCase } from '@vueuse/integrations/useChangeCase'

// `changeCase` will be a computed
const changeCase = useChangeCase('hello world', 'camelCase')
changeCase.value // helloWorld
changeCase.value = 'vue use'
changeCase.value // vueUse
// Supported methods
// export {
//   camelCase,
//   capitalCase,
//   constantCase,
//   dotCase,
//   headerCase,
//   noCase,
//   paramCase,
//   pascalCase,
//   pathCase,
//   sentenceCase,
//   snakeCase,
// } from 'change-case'
```


or passing a `ref` to it, the returned `computed` will change along with the source ref's changes.


Can be passed into `options` for customization




```
import { ref } from 'vue'
import { useChangeCase } from '@vueuse/integrations/useChangeCase'

const input = ref('helloWorld')
const changeCase = useChangeCase(input, 'camelCase', {
  delimiter: '-',
})
changeCase.value // hello-World
ref.value = 'vue use'
changeCase.value // vue-Use
```


Type Declarations
-----------------




```
export type ChangeCaseType = keyof typeof changeCase
export declare function useChangeCase(
  input: MaybeRef<string>,
  type: ChangeCaseType,
  options?: Options | undefined
): WritableComputedRef<string>
export declare function useChangeCase(
  input: MaybeRefOrGetter<string>,
  type: ChangeCaseType,
  options?: Options | undefined
): ComputedRef<string>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useChangeCase/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useChangeCase/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useChangeCase/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useChangeCase/>

useQRCode
=========




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 371 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | 2 weeks ago |


Wrapper for [`qrcode`](https://github.com/soldair/node-qrcode).

 Available in the [@vueuse/integrations](../readme) add-on. Install
-------




```
npm i qrcode
```


Usage
-----




```
import { useQRCode } from '@vueuse/integrations/useQRCode'

// `qrcode` will be a ref of data URL
const qrcode = useQRCode('text-to-encode')
```


or passing a `ref` to it, the returned data URL ref will change along with the source ref's changes.




```
import { ref } from 'vue'
import { useQRCode } from '@vueuse/integrations/useQRCode'

const text = ref('text-to-encode')
const qrcode = useQRCode(text)
```




```
<input v-model="text" type="text">
<img :src="qrcode" alt="QR Code" />
```


Type Declarations
-----------------




```
/**
 * Wrapper for qrcode.
 *
 * @see https://vueuse.org/useQRCode
 * @param text
 * @param options
 */
export declare function useQRCode(
  text: MaybeRefOrGetter<string>,
  options?: QRCode.QRCodeToDataURLOptions
): Ref<string>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useQRCode/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useQRCode/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useQRCode/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useQRCode/>

from / fromEvent
================


Wrappers around RxJS's [`from()`](https://rxjs.dev/api/index/function/from) and [`fromEvent()`](https://rxjs.dev/api/index/function/fromEvent) to allow them to accept `ref`s. Available in the [@vueuse/rxjs](../readme) add-on.


Usage
-----




|  |  |
| --- | --- |
|  Category  | [@RxJS](../../functions#category=%40RxJS) |
|  Export Size  | 153 B |
|  Package  | `@vueuse/rxjs` |
|  Last Changed  | 7 months ago |




```
import { ref } from 'vue'
import { from, fromEvent, toObserver, useSubscription } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map, mapTo, takeUntil, withLatestFrom } from 'rxjs/operators'

const count = ref(0)
const button = ref<HTMLButtonElement>(null)

useSubscription(
  interval(1000)
    .pipe(
      mapTo(1),
      takeUntil(fromEvent(button, 'click')),
      withLatestFrom(from(count, {
        immediate: true,
        deep: false,
      })),
      map(([curr, total]) => curr + total),
    )
    .subscribe(toObserver(count)), // same as ).subscribe(val => (count.value = val))
)
```


Type Declarations
-----------------




```
export declare function from<T>(
  value: ObservableInput<T> | Ref<T>,
  watchOptions?: WatchOptions
): Observable<T>
export declare function fromEvent<T extends HTMLElement>(
  value: MaybeRef<T>,
  event: string
): Observable<Event>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/from/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/from/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/rxjs/from/>

useFirestore
============




|  |  |
| --- | --- |
|  Category  | [@Firebase](../../functions#category=%40Firebase) |
|  Export Size  | 631 B |
|  Package  | `@vueuse/firebase` |
|  Last Changed  | 2 weeks ago |


Reactive [Firestore](https://firebase.google.com/docs/firestore) binding. Making it straightforward to **always keep your local data in sync** with remotes databases. Available in the [@vueuse/firebase](../readme) add-on.


Usage
-----




```
import { computed, ref } from 'vue'
import { initializeApp } from 'firebase/app'
import { collection, doc, getFirestore, limit, orderBy, query } from 'firebase/firestore'
import { useFirestore } from '@vueuse/firebase/useFirestore'

const app = initializeApp({ projectId: 'MY PROJECT ID' })
const db = getFirestore(app)

const todos = useFirestore(collection(db, 'todos'))

// or for doc reference
const user = useFirestore(doc(db, 'users', 'my-user-id'))

// you can also use ref value for reactive query
const postsLimit = ref(10)
const postsQuery = computed(() => query(collection(db, 'posts'), orderBy('createdAt', 'desc'), limit(postsLimit.value)))
const posts = useFirestore(postsQuery)

// you can use the boolean value to tell a query when it is ready to run
// when it gets falsy value, return the initial value
const userId = ref('')
const userQuery = computed(() => userId.value && doc(db, 'users', userId.value))
const userData = useFirestore(userQuery, null)
```


Share across instances
----------------------


You can reuse the db reference by passing `autoDispose: false`. You can also set an amount of milliseconds before auto disposing the db reference.


Note : Getting a not disposed db reference again don't cost a Firestore read.




```
const todos = useFirestore(collection(db, 'todos'), undefined, { autoDispose: false })
```


or use [`createGlobalState`](../../shared/createglobalstate/index) from the core package




```
// store.js
import { createGlobalState } from '@vueuse/core'
import { useFirestore } from '@vueuse/firebase/useFirestore'

export const useTodos = createGlobalState(
  () => useFirestore(collection(db, 'todos')),
)
```




```
// app.js
import { useTodos } from './store'

export default {
  setup() {
    const todos = useTodos()
    return { todos }
  },
}
```


Type Declarations
-----------------




```
export interface UseFirestoreOptions {
  errorHandler?: (err: Error) => void
  autoDispose?: boolean | number
}
export type FirebaseDocRef<T> = Query<T> | DocumentReference<T>
type Falsy = false | 0 | "" | null | undefined
export declare function useFirestore<T extends DocumentData>(
  maybeDocRef: MaybeRef<DocumentReference<T> | Falsy>,
  initialValue: T,
  options?: UseFirestoreOptions
): Ref<T | null>
export declare function useFirestore<T extends DocumentData>(
  maybeDocRef: MaybeRef<Query<T> | Falsy>,
  initialValue: T[],
  options?: UseFirestoreOptions
): Ref<T[]>
export declare function useFirestore<T extends DocumentData>(
  maybeDocRef: MaybeRef<DocumentReference<T> | Falsy>,
  initialValue?: T | undefined | null,
  options?: UseFirestoreOptions
): Ref<T | undefined | null>
export declare function useFirestore<T extends DocumentData>(
  maybeDocRef: MaybeRef<Query<T> | Falsy>,
  initialValue?: T[],
  options?: UseFirestoreOptions
): Ref<T[] | undefined>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/firebase/useFirestore/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/firebase/useFirestore/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/firebase/useFirestore/>

useJwt
======




|  |  |
| --- | --- |
|  Category  | [@Integrations](../../functions#category=%40Integrations) |
|  Export Size  | 313 B |
|  Package  | `@vueuse/integrations` |
|  Last Changed  | 2 weeks ago |


Wrapper for [`jwt-decode`](https://github.com/auth0/jwt-decode).

 Available in the [@vueuse/integrations](../readme) add-on. Install
-------




```
npm install jwt-decode
```


Usage
-----




```
import { defineComponent } from 'vue'
import { useJwt } from '@vueuse/integrations/useJwt'

export default defineComponent({
  setup() {
    const encodedJwt = ref('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyfQ.L8i6g3PfcHlioHCCPURC9pmXT7gdJpx3kOoyAfNUwCc')
    const { header, payload } = useJwt(encodedJwt)

    return { header, payload }
  },
})
```


Type Declarations
-----------------




```
export interface UseJwtOptions<Fallback> {
  /**
   * Value returned when encounter error on decoding
   *
   * @default null
   */
  fallbackValue?: Fallback
  /**
   * Error callback for decoding
   */
  onError?: (error: unknown) => void
}
export interface UseJwtReturn<Payload, Header, Fallback> {
  header: ComputedRef<Header | Fallback>
  payload: ComputedRef<Payload | Fallback>
}
/**
 * Reactive decoded jwt token.
 *
 * @see https://vueuse.org/useJwt
 * @param jwt
 */
export declare function useJwt<
  Payload extends object = JwtPayload,
  Header extends object = JwtHeader,
  Fallback = null
>(
  encodedJwt: MaybeRefOrGetter<string>,
  options?: UseJwtOptions<Fallback>
): UseJwtReturn<Payload, Header, Fallback>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useJwt/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useJwt/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/integrations/useJwt/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/integrations/useJwt/>

useSubject
==========




|  |  |
| --- | --- |
|  Category  | [@RxJS](../../functions#category=%40RxJS) |
|  Export Size  | 235 B |
|  Package  | `@vueuse/rxjs` |
|  Last Changed  | 4 months ago |


Bind an RxJS [`Subject`](https://rxjs.dev/guide/subject) to a `ref` and propagate value changes both ways.

 Available in the [@vueuse/rxjs](../readme) add-on. Usage
-----




```
import { useSubject } from '@vueuse/rxjs'
import { Subject } from 'rxjs'

const subject = new Subject()

// setup()
const subjectRef = useSubject(subject)
```


If you want to add custom error handling to a Subject that might error, you can supply an optional `onError` configuration. Without this, RxJS will treat any error in the supplied observable as an "unhandled error" and it will be thrown in a new call stack and reported to `window.onerror` (or `process.on('error')` if you happen to be in node).




```
import { useSubject } from '@vueuse/rxjs'
import { Subject } from 'rxjs'

const subject = new Subject()

// setup()
const subjectRef = useSubject(subject,
  {
    onError: (err) => {
      console.log(err.message) // "oops"
    },
  },
)
```


Type Declarations
-----------------




```
export interface UseSubjectOptions<I = undefined>
  extends Omit<UseObservableOptions<I>, "initialValue"> {}
export declare function useSubject<H>(
  subject: BehaviorSubject<H>,
  options?: UseSubjectOptions
): Ref<H>
export declare function useSubject<H>(
  subject: Subject<H>,
  options?: UseSubjectOptions
): Ref<H | undefined>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/useSubject/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/useSubject/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/useSubject/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/rxjs/useSubject/>

useObservable
=============




|  |  |
| --- | --- |
|  Category  | [@RxJS](../../functions#category=%40RxJS) |
|  Export Size  | 212 B |
|  Package  | `@vueuse/rxjs` |
|  Last Changed  | last year |


Use an RxJS [`Observable`](https://rxjs.dev/guide/observable), return a `ref`, and automatically unsubscribe from it when the component is unmounted. Available in the [@vueuse/rxjs](../readme) add-on.


Usage
-----




```
import { ref } from 'vue'
import { useObservable } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { mapTo, scan, startWith } from 'rxjs/operators'

// setup()
const count = useObservable(
  interval(1000).pipe(
    mapTo(1),
    startWith(0),
    scan((total, next) => next + total),
  ),
)
```


If you want to add custom error handling to an `Observable` that might error, you can supply an optional `onError` configuration. Without this, RxJS will treat any error in the supplied `Observable` as an "unhandled error" and it will be thrown in a new call stack and reported to `window.onerror` (or `process.on('error')` if you happen to be in Node).




```
import { ref } from 'vue'
import { useObservable } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map } from 'rxjs/operators'

// setup()
const count = useObservable(
  interval(1000).pipe(
    map((n) => {
      if (n === 10)
        throw new Error('oops')

      return n + n
    }),
  ),
  {
    onError: (err) => {
      console.log(err.message) // "oops"
    },
  },
)
```


Type Declarations
-----------------




```
export interface UseObservableOptions<I> {
  onError?: (err: any) => void
  /**
   * The value that should be set if the observable has not emitted.
   */
  initialValue?: I | undefined
}
export declare function useObservable<H, I = undefined>(
  observable: Observable<H>,
  options?: UseObservableOptions<I | undefined>
): Readonly<Ref<H | I>>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/useObservable/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/useObservable/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/rxjs/useObservable/>

useSubscription
===============




|  |  |
| --- | --- |
|  Category  | [@RxJS](../../functions#category=%40RxJS) |
|  Export Size  | 144 B |
|  Package  | `@vueuse/rxjs` |
|  Last Changed  | 2 years ago |


Use an RxJS [`Subscription`](https://rxjs.dev/guide/subscription) without worrying about unsubscribing from it or creating memory leaks. Available in the [@vueuse/rxjs](../readme) add-on.


Usage
-----




```
import { useSubscription } from '@vueuse/rxjs'
import { interval } from 'rxjs'

const count = ref(0)

// useSubscription call unsubscribe method before unmount the component
useSubscription(
  interval(1000)
    .subscribe(() => {
      count.value++
      console.log(count)
    }),
)
```


Type Declarations
-----------------




```
export declare function useSubscription(subscription: Unsubscribable): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/useSubscription/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/useSubscription/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/rxjs/useSubscription/>

toObserver
==========




|  |  |
| --- | --- |
|  Category  | [@RxJS](../../functions#category=%40RxJS) |
|  Export Size  | 88 B |
|  Package  | `@vueuse/rxjs` |
|  Last Changed  | 2 years ago |


Sugar function to convert a `ref` into an RxJS [Observer](https://rxjs.dev/guide/observer). Available in the [@vueuse/rxjs](../readme) add-on.


Usage
-----




```
import { ref } from 'vue'
import { from, fromEvent, toObserver, useSubscription } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map, mapTo, takeUntil, withLatestFrom } from 'rxjs/operators'

const count = ref(0)
const button = ref<HTMLButtonElement>(null)

useSubscription(
  interval(1000)
    .pipe(
      mapTo(1),
      takeUntil(fromEvent(button, 'click')),
      withLatestFrom(from(count).pipe(startWith(0))),
      map(([total, curr]) => curr + total),
    )
    .subscribe(toObserver(count)), // same as ).subscribe(val => (count.value = val))
)
```


Type Declarations
-----------------




```
export declare function toObserver<T>(value: Ref<T>): NextObserver<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/toObserver/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/rxjs/toObserver/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/rxjs/toObserver/>

useZoomLevel
============




|  |  |
| --- | --- |
|  Category  | [@Electron](../../functions#category=%40Electron) |
|  Export Size  | 281 B |
|  Package  | `@vueuse/electron` |
|  Last Changed  | last week |


Reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom level. Available in the [@vueuse/electron](../readme) add-on.


Usage
-----




```
import { useZoomLevel } from '@vueuse/electron'

// enable nodeIntegration if you don't provide webFrame explicitly
// @see: https://www.electronjs.org/docs/api/webview-tag#nodeintegration
// Ref result will return
const level = useZoomLevel()
console.log(level.value) // print current zoom level
level.value = 2 // change current zoom level
```


Set initial zoom level immediately




```
import { useZoomLevel } from '@vueuse/electron'

const level = useZoomLevel(2)
```


Pass a `ref` and the level will be updated when the source ref changes




```
import { useZoomLevel } from '@vueuse/electron'

const level = ref(1)

useZoomLevel(level) // zoom level will match with the ref

level.value = 2 // zoom level will change
```


Type Declarations
-----------------




```
export declare function useZoomLevel(level: MaybeRef<number>): Ref<number>
export declare function useZoomLevel(
  webFrame: WebFrame,
  level: MaybeRef<number>
): Ref<number>
export declare function useZoomLevel(webFrame: WebFrame): Ref<number>
export declare function useZoomLevel(): Ref<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/electron/useZoomLevel/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/electron/useZoomLevel/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/electron/useZoomLevel/>

useRTDB
=======




|  |  |
| --- | --- |
|  Category  | [@Firebase](../../functions#category=%40Firebase) |
|  Export Size  | 210 B |
|  Package  | `@vueuse/firebase` |
|  Last Changed  | 9 months ago |


Reactive [Firebase Realtime Database](https://firebase.google.com/docs/database) binding. Making it straightforward to **always keep your local data in sync** with remotes databases. Available in the [@vueuse/firebase](../readme) add-on.


Usage
-----




```
import { initializeApp } from 'firebase/app'
import { getDatabase } from 'firebase/database'
import { useRTDB } from '@vueuse/firebase/useRTDB'

const app = initializeApp({ /* config */ })
const db = getDatabase(app)

// in setup()
const todos = useRTDB(db.ref('todos'))
```


You can reuse the db reference by passing `autoDispose: false`




```
const todos = useRTDB(db.ref('todos'), { autoDispose: false })
```


or use [`createGlobalState`](../../shared/createglobalstate/index) from the core package




```
// store.js
import { createGlobalState } from '@vueuse/core'
import { useRTDB } from '@vueuse/firebase/useRTDB'

export const useTodos = createGlobalState(
  () => useRTDB(db.ref('todos')),
)
```




```
// app.js
import { useTodos } from './store'

const todos = useTodos()
```


Type Declarations
-----------------




```
export interface UseRTDBOptions {
  autoDispose?: boolean
}
/**
 * Reactive Firebase Realtime Database binding.
 *
 * @see https://vueuse.org/useRTDB
 */
export declare function useRTDB<T = any>(
  docRef: DatabaseReference,
  options?: UseRTDBOptions
): Ref<T | undefined>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/firebase/useRTDB/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/firebase/useRTDB/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/firebase/useRTDB/>

useAuth
=======




|  |  |
| --- | --- |
|  Category  | [@Firebase](../../functions#category=%40Firebase) |
|  Export Size  | 164 B |
|  Package  | `@vueuse/firebase` |
|  Last Changed  | 9 months ago |


Reactive [Firebase Auth](https://firebase.google.com/docs/auth) binding. It provides a reactive `user` and `isAuthenticated` so you can easily react to changes in the users' authentication status. Available in the [@vueuse/firebase](../readme) add-on.


Usage
-----




```
<script setup lang="ts">
import { initializeApp } from 'firebase/app'
import { GoogleAuthProvider, getAuth, signInWithPopup } from 'firebase/auth'
import { useAuth } from '@vueuse/firebase/useAuth'

const app = initializeApp({ /* config */ })
const auth = getAuth(app);
const { isAuthenticated, user } = useAuth(auth)

const signIn = () => signInWithPopup(auth, new GoogleAuthProvider())
</script>

<template>
  <pre v-if="isAuthenticated">{{ user }}</pre>
  <div v-else>
    <button @click="signIn">
      Sign In with Google
    </button>
  </div>
</template>
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UseFirebaseAuthOptions {
  isAuthenticated: ComputedRef<boolean>
  user: Ref<User | null>
}
/**
 * Reactive Firebase Auth binding
 *
 * @see https://vueuse.org/useAuth
 */
export declare function useAuth(auth: Auth): {
  isAuthenticated: ComputedRef<boolean>
  user: Ref<{
    readonly emailVerified: boolean
    readonly isAnonymous: boolean
    readonly metadata: {
      readonly creationTime?: string | undefined
      readonly lastSignInTime?: string | undefined
    }
    readonly providerData: {
      readonly displayName: string | null
      readonly email: string | null
      readonly phoneNumber: string | null
      readonly photoURL: string | null
      readonly providerId: string
      readonly uid: string
    }[]
    readonly refreshToken: string
    readonly tenantId: string | null
    delete: () => Promise<void>
    getIdToken: (forceRefresh?: boolean | undefined) => Promise<string>
    getIdTokenResult: (
      forceRefresh?: boolean | undefined
    ) => Promise<IdTokenResult>
    reload: () => Promise<void>
    toJSON: () => object
    readonly displayName: string | null
    readonly email: string | null
    readonly phoneNumber: string | null
    readonly photoURL: string | null
    readonly providerId: string
    readonly uid: string
  } | null>
}
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/firebase/useAuth/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/firebase/useAuth/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/firebase/useAuth/>

useIpcRenderer
==============




|  |  |
| --- | --- |
|  Category  | [@Electron](../../functions#category=%40Electron) |
|  Export Size  | 460 B |
|  Package  | `@vueuse/electron` |
|  Last Changed  | 9 months ago |


Provides [ipcRenderer](https://www.electronjs.org/docs/api/ipc-renderer) and all of its APIs. Available in the [@vueuse/electron](../readme) add-on.


Usage
-----




```
import { useIpcRenderer } from '@vueuse/electron'

// enable nodeIntegration if you don't provide ipcRenderer explicitly
// @see: https://www.electronjs.org/docs/api/webview-tag#nodeintegration
const ipcRenderer = useIpcRenderer()

// Ref result will return
const result = ipcRenderer.invoke<string>('custom-channel', 'some data')
const msg = computed(() => result.value?.msg)

// remove listener automatically on unmounted
ipcRenderer.on('custom-event', (event, ...args) => {
  console.log(args)
})
```


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Result from useIpcRenderer
 *
 * @see https://www.electronjs.org/docs/api/ipc-renderer
 */
export interface UseIpcRendererReturn {
  /**
   * Listens to channel, when a new message arrives listener would be called with listener(event, args...).
   * [ipcRenderer.removeListener](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovelistenerchannel-listener) automatically on unmounted.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendereronchannel-listener
   */
  on(channel: string, listener: IpcRendererListener): IpcRenderer
  /**
   * Adds a one time listener function for the event. This listener is invoked only the next time a message is sent to channel, after which it is removed.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendereroncechannel-listener
   */
  once(
    channel: string,
    listener: (event: IpcRendererEvent, ...args: any[]) => void
  ): IpcRenderer
  /**
   * Removes the specified listener from the listener array for the specified channel.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovelistenerchannel-listener
   */
  removeListener(
    channel: string,
    listener: (...args: any[]) => void
  ): IpcRenderer
  /**
   * Removes all listeners, or those of the specified channel.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovealllistenerschannel
   */
  removeAllListeners(channel: string): IpcRenderer
  /**
   * Send an asynchronous message to the main process via channel, along with arguments.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrenderersendchannel-args
   */
  send(channel: string, ...args: any[]): void
  /**
   * Returns Promise<any> - Resolves with the response from the main process.
   * Send a message to the main process via channel and expect a result ~~asynchronously~~.
   * As composition-api, it makes asynchronous operations look like synchronous.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererinvokechannel-args
   */
  invoke<T>(channel: string, ...args: any[]): Ref<T | null>
  /**
   * Returns any - The value sent back by the ipcMain handler.
   * Send a message to the main process via channel and expect a result synchronously.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrenderersendsyncchannel-args
   */
  sendSync<T>(channel: string, ...args: any[]): Ref<T | null>
  /**
   * Send a message to the main process, optionally transferring ownership of zero or more MessagePort objects.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererpostmessagechannel-message-transfer
   */
  postMessage(channel: string, message: any, transfer?: MessagePort[]): void
  /**
   * Sends a message to a window with webContentsId via channel.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrenderersendtowebcontentsid-channel-args
   */
  sendTo(webContentsId: number, channel: string, ...args: any[]): void
  /**
   * Like ipcRenderer.send but the event will be sent to the <webview> element in the host page instead of the main process.
   *
   * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrenderersendtohostchannel-args
   */
  sendToHost(channel: string, ...args: any[]): void
}
/**
 * Get the `ipcRenderer` module with all APIs.
 *
 * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrenderersendtohostchannel-args
 * @see https://vueuse.org/useIpcRenderer
 */
export declare function useIpcRenderer(
  ipcRenderer?: IpcRenderer
): UseIpcRendererReturn
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/electron/useIpcRenderer/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/electron/useIpcRenderer/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/electron/useIpcRenderer/>

useZoomFactor
=============




|  |  |
| --- | --- |
|  Category  | [@Electron](../../functions#category=%40Electron) |
|  Export Size  | 317 B |
|  Package  | `@vueuse/electron` |
|  Last Changed  | last week |


Reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom factor. Available in the [@vueuse/electron](../readme) add-on.


Usage
-----




```
import { useZoomFactor } from '@vueuse/electron'

// enable nodeIntegration if you don't provide webFrame explicitly
// @see: https://www.electronjs.org/docs/api/webview-tag#nodeintegration
// Ref result will return
const factor = useZoomFactor()
console.log(factor.value) // print current zoom factor
factor.value = 2 // change current zoom factor
```


Set initial zoom factor immediately




```
import { useZoomFactor } from '@vueuse/electron'

const factor = useZoomFactor(2)
```


Pass a `ref` and the factor will be updated when the source ref changes




```
import { useZoomFactor } from '@vueuse/electron'

const factor = ref(1)

useZoomFactor(factor) // zoom factor will match with the ref

factor.value = 2 // zoom factor will change
```


Type Declarations
-----------------




```
export declare function useZoomFactor(factor: MaybeRef<number>): Ref<number>
export declare function useZoomFactor(
  webFrame: WebFrame,
  factor: MaybeRef<number>
): Ref<number>
export declare function useZoomFactor(webFrame: WebFrame): Ref<number>
export declare function useZoomFactor(): Ref<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/electron/useZoomFactor/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/electron/useZoomFactor/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/electron/useZoomFactor/>

useIpcRendererOn
================




|  |  |
| --- | --- |
|  Category  | [@Electron](../../functions#category=%40Electron) |
|  Export Size  | 242 B |
|  Package  | `@vueuse/electron` |
|  Last Changed  | last week |


Use [ipcRenderer.on](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendereronchannel-listener) with ease and [ipcRenderer.removeListener](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovelistenerchannel-listener) automatically on unmounted. Available in the [@vueuse/electron](../readme) add-on.


Usage
-----




```
import { useIpcRendererOn } from '@vueuse/electron'

// enable nodeIntegration if you don't provide ipcRenderer explicitly
// @see: https://www.electronjs.org/docs/api/webview-tag#nodeintegration
// remove listener automatically on unmounted
useIpcRendererOn('custom-event', (event, ...args) => {
  console.log(args)
})
```


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Listens to channel, when a new message arrives listener would be called with listener(event, args...).
 * [ipcRenderer.removeListener](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovelistenerchannel-listener) automatically on unmounted.
 *
 * You need to provide `ipcRenderer` to this function.
 *
 * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendereronchannel-listener
 * @see https://vueuse.org/useIpcRendererOn
 */
export declare function useIpcRendererOn(
  ipcRenderer: IpcRenderer,
  channel: string,
  listener: IpcRendererListener
): IpcRenderer
/**
 * Listens to channel, when a new message arrives listener would be called with listener(event, args...).
 * [ipcRenderer.removeListener](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovelistenerchannel-listener) automatically on unmounted.
 *
 * `ipcRenderer` will be automatically gotten.
 *
 * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendereronchannel-listener
 * @see https://vueuse.org/useIpcRendererOn
 */
export declare function useIpcRendererOn(
  channel: string,
  listener: IpcRendererListener
): IpcRenderer
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/electron/useIpcRendererOn/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/electron/useIpcRendererOn/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/electron/useIpcRendererOn/>

useIpcRendererInvoke
====================




|  |  |
| --- | --- |
|  Category  | [@Electron](../../functions#category=%40Electron) |
|  Export Size  | 218 B |
|  Package  | `@vueuse/electron` |
|  Last Changed  | last week |


Reactive [ipcRenderer.invoke API](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererinvokechannel-args) result. Make asynchronous operations look synchronous. Available in the [@vueuse/electron](../readme) add-on.


Usage
-----




```
import { useIpcRendererInvoke } from '@vueuse/electron'

// enable nodeIntegration if you don't provide ipcRenderer explicitly
// @see: https://www.electronjs.org/docs/api/webview-tag#nodeintegration
// Ref result will return
const result = useIpcRendererInvoke<string>('custom-channel', 'some data')
const msg = computed(() => result.value?.msg)
```


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Returns Promise<any> - Resolves with the response from the main process.
 *
 * Send a message to the main process via channel and expect a result ~~asynchronously~~. As composition-api, it makes asynchronous operations look like synchronous.
 *
 * You need to provide `ipcRenderer` to this function.
 *
 * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererinvokechannel-args
 * @see https://vueuse.org/useIpcRendererInvoke
 */
export declare function useIpcRendererInvoke<T>(
  ipcRenderer: IpcRenderer,
  channel: string,
  ...args: any[]
): Ref<T | null>
/**
 * Returns Promise<any> - Resolves with the response from the main process.
 *
 * Send a message to the main process via channel and expect a result ~~asynchronously~~. As composition-api, it makes asynchronous operations look like synchronous.
 *
 * `ipcRenderer` will be automatically gotten.
 *
 * @see https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererinvokechannel-args
 * @see https://vueuse.org/useIpcRendererInvoke
 */
export declare function useIpcRendererInvoke<T>(
  channel: string,
  ...args: any[]
): Ref<T | null>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/electron/useIpcRendererInvoke/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/electron/useIpcRendererInvoke/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/electron/useIpcRendererInvoke/>

watchTriggerable
================




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 942 B |
|  Last Changed  | 2 weeks ago |


Watch that can be triggered manually


Usage
-----


A `watch` wrapper that supports manual triggering of `WatchCallback`, which returns an additional `trigger` to execute a `WatchCallback` immediately.




```
import { watchTriggerable } from '@vueuse/core'
import { nextTick, ref } from 'vue'

const source = ref(0)

const { trigger, ignoreUpdates } = watchTriggerable(
  source,
  v => console.log(`Changed to ${v}!`),
)

source.value = 'bar'
await nextTick() // logs: Changed to bar!

// Execution of WatchCallback via `trigger` does not require waiting
trigger() // logs: Changed to bar!
```


### 
`onCleanup`


When you want to manually call a `watch` that uses the onCleanup parameter; simply taking the `WatchCallback` out and calling it doesn't make it easy to implement the `onCleanup` parameter.


Using [`watchTriggerable`](index) will solve this problem.




```
import { watchTriggerable } from '@vueuse/core'
import { ref } from 'vue'

const source = ref(0)

const { trigger } = watchTriggerable(
  source,
  async (v, _, onCleanup) => {
    let canceled = false
    onCleanup(() => canceled = true)

    await new Promise(resolve => setTimeout(resolve, 500))
    if (canceled)
      return

    console.log(`The value is "${v}"\n`)
  },
)

source.value = 1 // no log
await trigger() // logs (after 500 ms): The value is "1"
```


Type Declarations
-----------------



Show Type Declarations

```
export interface WatchTriggerableReturn<FnReturnT = void>
  extends WatchIgnorableReturn {
  /** Execute `WatchCallback` immediately */
  trigger: () => FnReturnT
}
type OnCleanup = (cleanupFn: () => void) => void
export type WatchTriggerableCallback<V = any, OV = any, R = void> = (
  value: V,
  oldValue: OV,
  onCleanup: OnCleanup
) => R
export declare function watchTriggerable<
  T extends Readonly<WatchSource<unknown>[]>,
  FnReturnT
>(
  sources: [...T],
  cb: WatchTriggerableCallback<
    MapSources<T>,
    MapOldSources<T, true>,
    FnReturnT
  >,
  options?: WatchWithFilterOptions<boolean>
): WatchTriggerableReturn<FnReturnT>
export declare function watchTriggerable<T, FnReturnT>(
  source: WatchSource<T>,
  cb: WatchTriggerableCallback<T, T | undefined, FnReturnT>,
  options?: WatchWithFilterOptions<boolean>
): WatchTriggerableReturn<FnReturnT>
export declare function watchTriggerable<T extends object, FnReturnT>(
  source: T,
  cb: WatchTriggerableCallback<T, T | undefined, FnReturnT>,
  options?: WatchWithFilterOptions<boolean>
): WatchTriggerableReturn<FnReturnT>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchTriggerable/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchTriggerable/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchTriggerable/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchTriggerable/>

until
=====




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 595 B |
|  Last Changed  | 2 weeks ago |


Promised one-time watch for changes


Usage
-----


#### Wait for some async data to be ready




```
import { until, useAsyncState } from '@vueuse/core'

const { state, isReady } = useAsyncState(
  fetch('https://jsonplaceholder.typicode.com/todos/1').then(t => t.json()),
  {},
)

;(async () => {
  await until(isReady).toBe(true)

  console.log(state) // state is now ready!
})()
```


#### Wait for custom conditions



> You can use `invoke` to call the async function.
> 
> 




```
import { invoke, until, useCounter } from '@vueuse/core'

const { count } = useCounter()

invoke(async () => {
  await until(count).toMatch(v => v > 7)

  alert('Counter is now larger than 7!')
})
```


#### Timeout




```
// will be resolve until ref.value === true or 1000ms passed
await until(ref).toBe(true, { timeout: 1000 })

// will throw if timeout
try {
  await until(ref).toBe(true, { timeout: 1000, throwOnTimeout: true })
  // ref.value === true
}
catch (e) {
  // timeout
}
```


#### More Examples




```
await until(ref).toBe(true)
await until(ref).toMatch(v => v > 10 && v < 100)
await until(ref).changed()
await until(ref).changedTimes(10)
await until(ref).toBeTruthy()
await until(ref).toBeNull()

await until(ref).not.toBeNull()
await until(ref).not.toBeTruthy()
```


Type Declarations
-----------------



Show Type Declarations

```
export interface UntilToMatchOptions {
  /**
   * Milliseconds timeout for promise to resolve/reject if the when condition does not meet.
   * 0 for never timed out
   *
   * @default 0
   */
  timeout?: number
  /**
   * Reject the promise when timeout
   *
   * @default false
   */
  throwOnTimeout?: boolean
  /**
   * `flush` option for internal watch
   *
   * @default 'sync'
   */
  flush?: WatchOptions["flush"]
  /**
   * `deep` option for internal watch
   *
   * @default 'false'
   */
  deep?: WatchOptions["deep"]
}
export interface UntilBaseInstance<T, Not extends boolean = false> {
  toMatch<U extends T = T>(
    condition: (v: T) => v is U,
    options?: UntilToMatchOptions
  ): Not extends true ? Promise<Exclude<T, U>> : Promise<U>
  toMatch(
    condition: (v: T) => boolean,
    options?: UntilToMatchOptions
  ): Promise<T>
  changed(options?: UntilToMatchOptions): Promise<T>
  changedTimes(n?: number, options?: UntilToMatchOptions): Promise<T>
}
type Falsy = false | void | null | undefined | 0 | 0n | ""
export interface UntilValueInstance<T, Not extends boolean = false>
  extends UntilBaseInstance<T, Not> {
  readonly not: UntilValueInstance<T, Not extends true ? false : true>
  toBe<P = T>(
    value: MaybeRefOrGetter<P>,
    options?: UntilToMatchOptions
  ): Not extends true ? Promise<T> : Promise<P>
  toBeTruthy(
    options?: UntilToMatchOptions
  ): Not extends true ? Promise<T & Falsy> : Promise<Exclude<T, Falsy>>
  toBeNull(
    options?: UntilToMatchOptions
  ): Not extends true ? Promise<Exclude<T, null>> : Promise<null>
  toBeUndefined(
    options?: UntilToMatchOptions
  ): Not extends true ? Promise<Exclude<T, undefined>> : Promise<undefined>
  toBeNaN(options?: UntilToMatchOptions): Promise<T>
}
export interface UntilArrayInstance<T> extends UntilBaseInstance<T> {
  readonly not: UntilArrayInstance<T>
  toContains(
    value: MaybeRefOrGetter<ElementOf<ShallowUnwrapRef<T>>>,
    options?: UntilToMatchOptions
  ): Promise<T>
}
/**
 * Promised one-time watch for changes
 *
 * @see https://vueuse.org/until
 * @example
 * ```
 * const { count } = useCounter()
 *
 * await until(count).toMatch(v => v > 7)
 *
 * alert('Counter is now larger than 7!')
 * ```
 */
export declare function until<T extends unknown[]>(
  r: WatchSource<T> | MaybeRefOrGetter<T>
): UntilArrayInstance<T>
export declare function until<T>(
  r: WatchSource<T> | MaybeRefOrGetter<T>
): UntilValueInstance<T>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/until/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/until/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/until/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/until/>

watchThrottled
==============




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 831 B |
|  Last Changed  | 2 weeks ago |
|  Alias  | `throttledWatch` |


Throttled watch.


Usage
-----


Similar to `watch`, but offering an extra option `throttle` which will be applied to the callback function.




```
import { watchThrottled } from '@vueuse/core'

watchThrottled(
  source,
  () => { console.log('changed!') },
  { throttle: 500 },
)
```


It's essentially a shorthand for the following code:




```
import { throttleFilter, watchWithFilter } from '@vueuse/core'

watchWithFilter(
  source,
  () => { console.log('changed!') },
  {
    eventFilter: throttleFilter(500),
  },
)
```


Type Declarations
-----------------




```
export interface WatchThrottledOptions<Immediate>
  extends WatchOptions<Immediate> {
  throttle?: MaybeRefOrGetter<number>
  trailing?: boolean
  leading?: boolean
}
export declare function watchThrottled<
  T extends Readonly<WatchSource<unknown>[]>,
  Immediate extends Readonly<boolean> = false
>(
  sources: [...T],
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options?: WatchThrottledOptions<Immediate>
): WatchStopHandle
export declare function watchThrottled<
  T,
  Immediate extends Readonly<boolean> = false
>(
  source: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchThrottledOptions<Immediate>
): WatchStopHandle
export declare function watchThrottled<
  T extends object,
  Immediate extends Readonly<boolean> = false
>(
  source: T,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchThrottledOptions<Immediate>
): WatchStopHandle
export { watchThrottled as throttledWatch }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchThrottled/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchThrottled/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchThrottled/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchThrottled/>

watchIgnorable
==============




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 708 B |
|  Last Changed  | 10 months ago |
|  Alias  | `ignorableWatch` |


Ignorable watch


Usage
-----


Extended `watch` that returns extra `ignoreUpdates(updater)` and `ignorePrevAsyncUpdates()` to ignore particular updates to the source.




```
import { watchIgnorable } from '@vueuse/core'
import { nextTick, ref } from 'vue'

const source = ref('foo')

const { stop, ignoreUpdates } = watchIgnorable(
  source,
  v => console.log(`Changed to ${v}!`),
)

source.value = 'bar'
await nextTick() // logs: Changed to bar!

ignoreUpdates(() => {
  source.value = 'foobar'
})
await nextTick() // (nothing happened)

source.value = 'hello'
await nextTick() // logs: Changed to hello!

ignoreUpdates(() => {
  source.value = 'ignored'
})
source.value = 'logged'

await nextTick() // logs: Changed to logged!
```


Flush timing
------------


[`watchIgnorable`](index) accepts the same options as `watch` and uses the same defaults. So, by default the composable works using `flush: 'pre'`.



`ignorePrevAsyncUpdates`
-------------------------


This feature is only for async flush `'pre'` and `'post'`. If `flush: 'sync'` is used, `ignorePrevAsyncUpdates()` is a no-op as the watch will trigger immediately after each update to the source. It is still provided for sync flush so the code can be more generic.




```
import { watchIgnorable } from '@vueuse/core'
import { nextTick, ref } from 'vue'

const source = ref('foo')

const { ignorePrevAsyncUpdates } = watchIgnorable(
  source,
  v => console.log(`Changed to ${v}!`),
)

source.value = 'bar'
await nextTick() // logs: Changed to bar!

source.value = 'good'
source.value = 'by'
ignorePrevAsyncUpdates()

await nextTick() // (nothing happened)

source.value = 'prev'
ignorePrevAsyncUpdates()
source.value = 'after'

await nextTick() // logs: Changed to after!
```


Recommended Readings
--------------------


* [Ignorable Watch](https://patak.dev/vue/ignorable-watch.html) - by [@matias-capeletto](https://github.com/matias-capeletto)


Type Declarations
-----------------



Show Type Declarations

```
export type IgnoredUpdater = (updater: () => void) => void
export interface WatchIgnorableReturn {
  ignoreUpdates: IgnoredUpdater
  ignorePrevAsyncUpdates: () => void
  stop: WatchStopHandle
}
export declare function watchIgnorable<
  T extends Readonly<WatchSource<unknown>[]>,
  Immediate extends Readonly<boolean> = false
>(
  sources: [...T],
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options?: WatchWithFilterOptions<Immediate>
): WatchIgnorableReturn
export declare function watchIgnorable<
  T,
  Immediate extends Readonly<boolean> = false
>(
  source: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>
): WatchIgnorableReturn
export declare function watchIgnorable<
  T extends object,
  Immediate extends Readonly<boolean> = false
>(
  source: T,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>
): WatchIgnorableReturn
export { watchIgnorable as ignorableWatch }
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchIgnorable/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchIgnorable/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchIgnorable/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchIgnorable/>

watchPausable
=============




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 674 B |
|  Last Changed  | 7 months ago |
|  Alias  | `pausableWatch` |


Pausable watch


Usage
-----


Use as normal the `watch`, but return extra `pause()` and `resume()` functions to control.




```
import { watchPausable } from '@vueuse/core'
import { nextTick, ref } from 'vue'

const source = ref('foo')

const { stop, pause, resume } = watchPausable(
  source,
  v => console.log(`Changed to ${v}!`),
)

source.value = 'bar'
await nextTick() // Changed to bar!

pause()

source.value = 'foobar'
await nextTick() // (nothing happend)

resume()

source.value = 'hello'
await nextTick() // Changed to hello!
```


Type Declarations
-----------------




```
export interface WatchPausableReturn extends Pausable {
  stop: WatchStopHandle
}
export declare function watchPausable<
  T extends Readonly<WatchSource<unknown>[]>,
  Immediate extends Readonly<boolean> = false
>(
  sources: [...T],
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options?: WatchWithFilterOptions<Immediate>
): WatchPausableReturn
export declare function watchPausable<
  T,
  Immediate extends Readonly<boolean> = false
>(
  source: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>
): WatchPausableReturn
export declare function watchPausable<
  T extends object,
  Immediate extends Readonly<boolean> = false
>(
  source: T,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>
): WatchPausableReturn
export { watchPausable as pausableWatch }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchPausable/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchPausable/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchPausable/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchPausable/>

useTimeout
==========




|  |  |
| --- | --- |
|  Category  | [Animation](../../functions#category=Animation) |
|  Export Size  | 565 B |
|  Last Changed  | 7 months ago |


Update value after a given time with controls.


Usage
-----




```
import { promiseTimeout, useTimeout } from '@vueuse/core'

const ready = useTimeout(1000)
```




```
const { ready, start, stop } = useTimeout(1000, { controls: true })
```




```
console.log(ready.value) // false

await promiseTimeout(1200)

console.log(ready.value) // true
```


Type Declarations
-----------------




```
export interface UseTimeoutOptions<Controls extends boolean>
  extends UseTimeoutFnOptions {
  /**
   * Expose more controls
   *
   * @default false
   */
  controls?: Controls
  /**
   * Callback on timeout
   */
  callback?: Fn
}
/**
 * Update value after a given time with controls.
 *
 * @see   {@link https://vueuse.org/useTimeout}
 * @param interval
 * @param options
 */
export declare function useTimeout(
  interval?: number,
  options?: UseTimeoutOptions<false>
): ComputedRef<boolean>
export declare function useTimeout(
  interval: number,
  options: UseTimeoutOptions<true>
): {
  ready: ComputedRef<boolean>
} & Stoppable
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useTimeout/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useTimeout/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useTimeout/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useTimeout/>

refDebounced
============




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 423 B |
|  Last Changed  | 2 weeks ago |
|  Alias  | `useDebounce``debouncedRef` |
|  Related  | [`useThrottleFn`](../usethrottlefn/index) |


Debounce execution of a ref value.


Usage
-----




```
import { refDebounced } from '@vueuse/core'

const input = ref('foo')
const debounced = refDebounced(input, 1000)

input.value = 'bar'
console.log(debounced.value) // 'foo'

await sleep(1100)

console.log(debounced.value) // 'bar'
```


You can also pass an optional 3rd parameter including maxWait option. See [`useDebounceFn`](../usedebouncefn/index) for details.


Recommended Reading
-------------------


* [**Debounce vs Throttle**: Definitive Visual Guide](https://redd.one/blog/debounce-vs-throttle)


Type Declarations
-----------------




```
/**
 * Debounce updates of a ref.
 *
 * @return A new debounced ref.
 */
export declare function refDebounced<T>(
  value: Ref<T>,
  ms?: MaybeRefOrGetter<number>,
  options?: DebounceFilterOptions
): Readonly<Ref<T>>
export { refDebounced as useDebounce, refDebounced as debouncedRef }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/refDebounced/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/refDebounced/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/refDebounced/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/refDebounced/>

watchAtMost
===========




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 510 B |
|  Last Changed  | 2 weeks ago |


`watch` with the number of times triggered.


Usage
-----


Similar to `watch` with an extra option `count` which set up the number of times the callback function is triggered. After the count is reached, the watch will be stopped automatically.




```
import { watchAtMost } from '@vueuse/core'

watchAtMost(
  source,
  () => { console.log('trigger!') }, // triggered it at most 3 times
  {
    count: 3, // the number of times triggered
  },
)
```


Type Declarations
-----------------




```
export interface WatchAtMostOptions<Immediate>
  extends WatchWithFilterOptions<Immediate> {
  count: MaybeRefOrGetter<number>
}
export interface WatchAtMostReturn {
  stop: WatchStopHandle
  count: Ref<number>
}
export declare function watchAtMost<
  T extends Readonly<WatchSource<unknown>[]>,
  Immediate extends Readonly<boolean> = false
>(
  sources: [...T],
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options: WatchAtMostOptions<Immediate>
): WatchAtMostReturn
export declare function watchAtMost<
  T,
  Immediate extends Readonly<boolean> = false
>(
  sources: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options: WatchAtMostOptions<Immediate>
): WatchAtMostReturn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchAtMost/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchAtMost/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchAtMost/>

refWithControl
==============




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 474 B |
|  Last Changed  | 7 months ago |
|  Alias  | `controlledRef` |
|  Related  | [`computedWithControl`](../computedwithcontrol/index) |


Fine-grained controls over ref and its reactivity.



**WARNING**This function only works for Vue 3



Usage
-----


[`refWithControl`](index) uses [`extendRef`](../extendref/index) to provide two extra functions [`get`](../get/index) and [`set`](../set/index) to have better control over when it should track/trigger the reactivity.




```
import { refWithControl } from '@vueuse/core'

const num = refWithControl(0)
const doubled = computed(() => num.value * 2)

// just like normal ref
num.value = 42
console.log(num.value) // 42
console.log(doubled.value) // 84

// set value without triggering the reactivity
num.set(30, false)
console.log(num.value) // 30
console.log(doubled.value) // 84 (doesn't update)

// get value without tracking the reactivity
watchEffect(() => {
  console.log(num.peek())
}) // 30

num.value = 50 // watch effect wouldn't be triggered since it collected nothing.
console.log(doubled.value) // 100 (updated again since it's a reactive set)
```


### 
`peek`, `lay`, `untrackedGet`, `silentSet`


We also provide some shorthands for doing the get/set without track/triggering the reactivity system. The following lines are equivalent.




```
const foo = refWithControl('foo')
```




```
// getting
foo.get(false)
foo.untrackedGet()
foo.peek() // an alias for `untrackedGet`
```




```
// setting
foo.set('bar', false)
foo.silentSet('bar')
foo.lay('bar') // an alias for `silentSet`
```


Configurations
--------------


### 
`onBeforeChange()`


`onBeforeChange` option is offered to give control over if a new value should be accepted. For example:




```
const num = refWithControl(0, {
  onBeforeChange(value, oldValue) {
    // disallow changes larger then ±5 in one operation
    if (Math.abs(value - oldValue) > 5)
      return false // returning `false` to dismiss the change
  },
})

num.value += 1
console.log(num.value) // 1

num.value += 6
console.log(num.value) // 1 (change been dismissed)
```


### 
`onChanged()`


`onChanged` option offers a similar functionally as Vue's `watch` but being synchronoused with less overhead compare to `watch`.




```
const num = refWithControl(0, {
  onChanged(value, oldValue) {
    console.log(value)
  },
})
```


Type Declarations
-----------------




```
export interface ControlledRefOptions<T> {
  /**
   * Callback function before the ref changing.
   *
   * Returning `false` to dismiss the change.
   */
  onBeforeChange?: (value: T, oldValue: T) => void | boolean
  /**
   * Callback function after the ref changed
   *
   * This happens synchronously, with less overhead compare to `watch`
   */
  onChanged?: (value: T, oldValue: T) => void
}
/**
 * Explicitly define the deps of computed.
 *
 * @param source
 * @param fn
 */
export declare function refWithControl<T>(
  initial: T,
  options?: ControlledRefOptions<T>
): ShallowUnwrapRef<{
  get: (tracking?: boolean) => T
  set: (value: T, triggering?: boolean) => void
  untrackedGet: () => T
  silentSet: (v: T) => void
  peek: () => T
  lay: (v: T) => void
}> &
  Ref<T>
/**
 * Alias for `refWithControl`
 */
export declare const controlledRef: typeof refWithControl
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/refWithControl/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/refWithControl/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/refWithControl/>

useThrottleFn
=============




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 401 B |
|  Last Changed  | 2 weeks ago |
|  Related  | [`refDebounced`](../refdebounced/index)[`refThrottled`](../refthrottled/index)[`useDebounceFn`](../usedebouncefn/index) |


Throttle execution of a function. Especially useful for rate limiting execution of handlers on events like resize and scroll.



> Throttle is a spring that throws balls: after a ball flies out it needs some time to shrink back, so it cannot throw any more balls unless it's ready.
> 
> 


Usage
-----




```
import { useThrottleFn } from '@vueuse/core'

const throttledFn = useThrottleFn(() => {
  // do something, it will be called at most 1 time per second
}, 1000)

window.addEventListener('resize', throttledFn)
```


Recommended Reading
-------------------


* [**Debounce vs Throttle**: Definitive Visual Guide](https://redd.one/blog/debounce-vs-throttle)


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Throttle execution of a function. Especially useful for rate limiting
 * execution of handlers on events like resize and scroll.
 *
 * @param   fn             A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
 *                                    to `callback` when the throttled-function is executed.
 * @param   ms             A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
 *
 * @param [trailing=false] if true, call fn again after the time is up
 *
 * @param [leading=true] if true, call fn on the leading edge of the ms timeout
 *
 * @param [rejectOnCancel=false] if true, reject the last call if it's been cancel
 *
 * @return  A new, throttled, function.
 */
export declare function useThrottleFn<T extends FunctionArgs>(
  fn: T,
  ms?: MaybeRefOrGetter<number>,
  trailing?: boolean,
  leading?: boolean,
  rejectOnCancel?: boolean
): PromisifyFn<T>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useThrottleFn/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useThrottleFn/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useThrottleFn/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useThrottleFn/>

useDateFormat
=============




|  |  |
| --- | --- |
|  Category  | [Time](../../functions#category=Time) |
|  Export Size  | 779 B |
|  Last Changed  | 3 days ago |


Get the formatted date according to the string of tokens passed in, inspired by [dayjs](https://github.com/iamkun/dayjs).


**List of all available formats (HH:mm:ss by default):**




| Format | Output | Description |
| --- | --- | --- |
| `YY` | 18 | Two-digit year |
| `YYYY` | 2018 | Four-digit year |
| `M` | 1-12 | The month, beginning at 1 |
| `MM` | 01-12 | The month, 2-digits |
| `MMM` | Jan-Dec | The abbreviated month name |
| `MMMM` | January-December | The full month name |
| `D` | 1-31 | The day of the month |
| `DD` | 01-31 | The day of the month, 2-digits |
| `H` | 0-23 | The hour |
| `HH` | 00-23 | The hour, 2-digits |
| `h` | 1-12 | The hour, 12-hour clock |
| `hh` | 01-12 | The hour, 12-hour clock, 2-digits |
| `m` | 0-59 | The minute |
| `mm` | 00-59 | The minute, 2-digits |
| `s` | 0-59 | The second |
| `ss` | 00-59 | The second, 2-digits |
| `SSS` | 000-999 | The millisecond, 3-digits |
| `A` | AM PM | The meridiem |
| `AA` | A.M. P.M. | The meridiem, periods |
| `a` | am pm | The meridiem, lowercase |
| `aa` | a.m. p.m. | The meridiem, lowercase and periods |
| `d` | 0-6 | The day of the week, with Sunday as 0 |
| `dd` | S-S | The min name of the day of the week |
| `ddd` | Sun-Sat | The short name of the day of the week |
| `dddd` | Sunday-Saturday | The name of the day of the week |


* Meridiem is customizable by defining `customMeridiem` in `options`.


Usage
-----


### Basic




```
<script setup lang="ts">

import { useNow, useDateFormat } from '@vueuse/core'

const formatted = useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss')

</script>

<template>
  <div>{{ formatted }}</div>
</template>
```


### Use with locales




```
<script setup lang="ts">

import { useNow, useDateFormat } from '@vueuse/core'

const formatted = useDateFormat(useNow(), 'YYYY-MM-DD (ddd)', { locales: 'en-US' })

</script>

<template>
  <div>{{ formatted }}</div>
</template>
```


### Use with custom meridiem




```
<script setup lang="ts">

import { useDateFormat } from '@vueuse/core'

const customMeridiem = (hours: number, minutes: number, isLowercase?: boolean, hasPeriod?: boolean) => {
  const m = hours > 11 ? (isLowercase ? 'μμ' : 'ΜΜ') : (isLowercase ? 'πμ' : 'ΠΜ')
  return hasPeriod ? m.split('').reduce((acc, current) => acc += `${current}.`, '') : m
}

const am = useDateFormat('2022-01-01 05:05:05', 'hh:mm:ss A', { customMeridiem })
// am.value = '05:05:05 ΠΜ'
const pm = useDateFormat('2022-01-01 17:05:05', 'hh:mm:ss AA', { customMeridiem })
// pm.value = '05:05:05 Μ.Μ.'
</script>
```


Type Declarations
-----------------



Show Type Declarations

```
export type DateLike = Date | number | string | undefined
export interface UseDateFormatOptions {
  /**
   * The locale(s) to used for dd/ddd/dddd/MMM/MMMM format
   *
   * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
   */
  locales?: Intl.LocalesArgument
  /**
   * A custom function to re-modify the way to display meridiem
   *
   */
  customMeridiem?: (
    hours: number,
    minutes: number,
    isLowercase?: boolean,
    hasPeriod?: boolean
  ) => string
}
export declare function formatDate(
  date: Date,
  formatStr: string,
  options?: UseDateFormatOptions
): string
export declare function normalizeDate(date: DateLike): Date
/**
 * Get the formatted date according to the string of tokens passed in.
 *
 * @see https://vueuse.org/useDateFormat
 * @param date - The date to format, can either be a `Date` object, a timestamp, or a string
 * @param formatStr - The combination of tokens to format the date
 * @param options - UseDateFormatOptions
 */
export declare function useDateFormat(
  date: MaybeRefOrGetter<DateLike>,
  formatStr?: MaybeRefOrGetter<string>,
  options?: UseDateFormatOptions
): ComputedRef<string>
export type UseDateFormatReturn = ReturnType<typeof useDateFormat>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useDateFormat/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useDateFormat/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useDateFormat/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useDateFormat/>

refThrottled
============




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 458 B |
|  Last Changed  | last year |
|  Alias  | `useThrottle``throttledRef` |
|  Related  | [`useThrottleFn`](../usethrottlefn/index) |


Throttle changing of a ref value.


Usage
-----




```
import { refThrottled } from '@vueuse/core'

const input = ref('')
const throttled = refThrottled(input, 1000)
```


### Trailing


If you don't want to watch trailing changes, set 3rd param `false` (it's `true` by default):




```
import { refThrottled } from '@vueuse/core'

const input = ref('')
const throttled = refThrottled(input, 1000, false)
```


### Leading


Allows the callback to be invoked immediately (on the leading edge of the `ms` timeout). If you don't want this behavior, set the 4th param `false` (it's `true` by default):




```
import { refThrottled } from '@vueuse/core'

const input = ref('')
const throttled = refThrottled(input, 1000, undefined, false)
```


Recommended Reading
-------------------


* [Debounce vs Throttle: Definitive Visual Guide](https://redd.one/blog/debounce-vs-throttle)
* [Debouncing and Throttling Explained Through Examples](https://css-tricks.com/debouncing-throttling-explained-examples/)


Type Declarations
-----------------




```
/**
 * Throttle execution of a function. Especially useful for rate limiting
 * execution of handlers on events like resize and scroll.
 *
 * @param value Ref value to be watched with throttle effect
 * @param  delay  A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
 * @param [trailing=true] if true, update the value again after the delay time is up
 * @param [leading=true] if true, update the value on the leading edge of the ms timeout
 */
export declare function refThrottled<T>(
  value: Ref<T>,
  delay?: number,
  trailing?: boolean,
  leading?: boolean
): Ref<T>
export { refThrottled as useThrottle, refThrottled as throttledRef }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/refThrottled/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/refThrottled/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/refThrottled/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/refThrottled/>

reactivePick
============




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 454 B |
|  Last Changed  | 2 weeks ago |


Reactively pick fields from a reactive object.


Usage
-----


### Basic Usage




```
import { reactivePick } from '@vueuse/core'

const obj = reactive({
  x: 0,
  y: 0,
  elementX: 0,
  elementY: 0,
})

const picked = reactivePick(obj, 'x', 'elementX') // { x: number, elementX: number }
```


### Predicate Usage




```
import { reactivePick } from '@vueuse/core'

const source = reactive({
  foo: 'foo',
  bar: 'bar',
  baz: 'baz',
  qux: true,
})
const state = reactivePick(source, (value, key) => key !== 'bar' && value !== true)
// { foo: string, baz: string }
source.qux = false
// { foo: string, baz: string, qux: boolean }
```


### Scenarios


#### Selectively passing props to child




```
<script setup>
import { reactivePick } from '@vueuse/core'

const props = defineProps({
  value: {
    default: 'value',
  },
  color: {
    type: String,
  },
  font: {
    type: String,
  }
})

const childProps = reactivePick(props, 'color', 'font')
</script>

<template>
  <div>
    <!-- only passes "color" and "font" props to child -->
    <ChildComp v-bind="childProps" />
  </div>
</template>
```


#### Selectively wrap reactive object


Instead of doing this




```
import { reactive } from 'vue'
import { useElementBounding } from '@vueuse/core'

const { height, width } = useElementBounding() // object of refs
const size = reactive({ height, width })
```


Now we can just have this




```
import { reactivePick, useElementBounding } from '@vueuse/core'

const size = reactivePick(useElementBounding(), 'height', 'width')
```


Type Declarations
-----------------




```
export type ReactivePickPredicate<T> = (
  value: T[keyof T],
  key: keyof T
) => boolean
export declare function reactivePick<T extends object, K extends keyof T>(
  obj: T,
  ...keys: (K | K[])[]
): {
  [S in K]: UnwrapRef<T[S]>
}
export declare function reactivePick<T extends object>(
  obj: T,
  predicate: ReactivePickPredicate<T>
): {
  [S in keyof T]?: UnwrapRef<T[S]>
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactivePick/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactivePick/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/reactivePick/>

toRefs
======




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 451 B |
|  Last Changed  | 10 months ago |


Extended [`toRefs`](https://v3.vuejs.org/api/refs-api.html#torefs) that also accepts refs of an object.


Usage
-----




```
import { toRefs } from '@vueuse/core'
import { reactive, ref } from 'vue'

const objRef = ref({ a: 'a', b: 0 })
const arrRef = ref(['a', 0])

const { a, b } = toRefs(objRef)
const [ a, b ] = toRefs(arrRef)

const obj = reactive({ a: 'a', b: 0 })
const arr = reactive(['a', 0])

const { a, b } = toRefs(obj)
const [ a, b ] = toRefs(arr)
```


Use-cases
---------


### Destructuring a props object




```
<template>
  <div>
    <input v-model="a" type="text" />
    <input v-model="b" type="text" />
  </div>
</template>

<script lang="ts">
import { toRefs, useVModel } from '@vueuse/core'

export default {
  setup(props) {
    const refs = toRefs(useVModel(props, 'data'))

    console.log(refs.a.value) // props.data.a
    refs.a.value = 'a' // emit('update:data', { ...props.data, a: 'a' })

    return { ...refs }
  }
}
</script>
```


Type Declarations
-----------------




```
/**
 * Extended `toRefs` that also accepts refs of an object.
 *
 * @see https://vueuse.org/toRefs
 * @param objectRef A ref or normal object or array.
 */
export declare function toRefs<T extends object>(
  objectRef: MaybeRef<T>
): ToRefs<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/toRefs/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/toRefs/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/toRefs/>

computedEager
=============




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 398 B |
|  Last Changed  | last year |
|  Alias  | `eagerComputed` |


Eager computed without lazy evaluation.


Learn more at [Vue: When a computed property can be the wrong tool](https://dev.to/linusborg/vue-when-a-computed-property-can-be-the-wrong-tool-195j).


* Use `computed()` when you have a complex calculation going on, which can actually profit from caching and lazy evaluation and should only be (re-)calculated if really necessary.
* Use `computedEager()` when you have a simple operation, with a rarely changing return value – often a boolean.


Usage
-----




```
import { computedEager } from '@vueuse/core'

const todos = ref([])
const hasOpenTodos = computedEager(() => !!todos.length)

console.log(hasOpenTodos.value) // false
toTodos.value.push({ title: 'Learn Vue' })
console.log(hasOpenTodos.value) // true
```


Type Declarations
-----------------




```
export declare function computedEager<T>(
  fn: () => T,
  options?: WatchOptionsBase
): Readonly<Ref<T>>
export { computedEager as eagerComputed }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/computedEager/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/computedEager/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/computedEager/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/computedEager/>

reactiveOmit
============




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 381 B |
|  Last Changed  | 2 weeks ago |


Reactively omit fields from a reactive object.


Usage
-----


### Basic Usage




```
import { reactiveOmit } from '@vueuse/core'

const obj = reactive({
  x: 0,
  y: 0,
  elementX: 0,
  elementY: 0,
})

const picked = reactiveOmit(obj, 'x', 'elementX') // { y: number, elementY: number }
```


### Predicate Usage




```
import { reactiveOmit } from '@vueuse/core'

const obj = reactive({
  bar: 'bar',
  baz: 'should be omit',
  foo: 'foo2',
  qux: true,
})

const picked = reactiveOmit(obj, (key, value) => key === 'baz' || value === true)
// { bar: string, foo: string }
```


### Scenarios


#### Selectively passing props to child




```
<script setup>
import { reactiveOmit } from '@vueuse/core'

const props = defineProps({
  value: {
    default: 'value',
  },
  color: {
    type: String,
  },
  font: {
    type: String,
  }
})

const childProps = reactiveOmit(props, 'value')
</script>

<template>
  <div>
    <!-- only passes "color" and "font" props to child -->
    <ChildComp v-bind="childProps" />
  </div>
</template>
```


Type Declarations
-----------------




```
export type ReactiveOmitPredicate<T> = (
  value: T[keyof T],
  key: keyof T
) => boolean
export declare function reactiveOmit<T extends object, K extends keyof T>(
  obj: T,
  ...keys: (K | K[])[]
): Omit<T, K>
export declare function reactiveOmit<T extends object>(
  obj: T,
  predicate: ReactiveOmitPredicate<T>
): Partial<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactiveOmit/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactiveOmit/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/reactiveOmit/>

watchWithFilter
===============




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 373 B |
|  Last Changed  | 7 months ago |


`watch` with additional EventFilter control.


Usage
-----


Similar to `watch`, but offering an extra option `eventFilter` which will be applied to the callback function.




```
import { debounceFilter, watchWithFilter } from '@vueuse/core'

watchWithFilter(
  source,
  () => { console.log('changed!') }, // callback will be called in 500ms debounced manner
  {
    eventFilter: debounceFilter(500), // throttledFilter, pausabledFilter or custom filters
  },
)
```


Type Declarations
-----------------




```
export interface WatchWithFilterOptions<Immediate>
  extends WatchOptions<Immediate>,
    ConfigurableEventFilter {}
export declare function watchWithFilter<
  T extends Readonly<WatchSource<unknown>[]>,
  Immediate extends Readonly<boolean> = false
>(
  sources: [...T],
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options?: WatchWithFilterOptions<Immediate>
): WatchStopHandle
export declare function watchWithFilter<
  T,
  Immediate extends Readonly<boolean> = false
>(
  source: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>
): WatchStopHandle
export declare function watchWithFilter<
  T extends object,
  Immediate extends Readonly<boolean> = false
>(
  source: T,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>
): WatchStopHandle
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchWithFilter/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchWithFilter/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchWithFilter/>

useDebounceFn
=============




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 372 B |
|  Last Changed  | 2 weeks ago |
|  Related  | [`useThrottleFn`](../usethrottlefn/index) |


Debounce execution of a function.



> Debounce is an overloaded waiter: if you keep asking him your requests will be ignored until you stop and give him some time to think about your latest inquiry.
> 
> 


Usage
-----




```
import { useDebounceFn } from '@vueuse/core'

const debouncedFn = useDebounceFn(() => {
  // do something
}, 1000)

window.addEventListener('resize', debouncedFn)
```


You can also pass a 3rd parameter to this, with a maximum wait time, similar to [lodash debounce](https://lodash.com/docs/4.17.15#debounce)




```
import { useDebounceFn } from '@vueuse/core'

// If no invokation after 5000ms due to repeated input,
// the function will be called anyway.
const debouncedFn = useDebounceFn(() => {
  // do something
}, 1000, { maxWait: 5000 })

window.addEventListener('resize', debouncedFn)
```


Optionally, you can get the return value of the function using promise operations.




```
import { useDebounceFn } from '@vueuse/core'

const debouncedRequest = useDebounceFn(() => 'response', 1000)

debouncedRequest().then((value) => {
  console.log(value) // 'response'
})

// or use async/await
async function doRequest() {
  const value = await debouncedRequest()
  console.log(value) // 'response'
}
```


Since unhandled rejection error is quite annoying when developer doesn't need the return value, the promise will **NOT** be rejected if the function is canceled **by default**. You need to specify the option `rejectOnCancel: true` to capture the rejection.




```
import { useDebounceFn } from '@vueuse/core'

const debouncedRequest = useDebounceFn(() => 'response', 1000, { rejectOnCancel: true })

debouncedRequest()
  .then((value) => {
    // do something
  })
  .catch(() => {
    // do something when canceled
  })

// calling it again will cancel the previous request and gets rejected
setTimeout(debouncedRequest, 500)
```


Recommended Reading
-------------------


* [**Debounce vs Throttle**: Definitive Visual Guide](https://redd.one/blog/debounce-vs-throttle)


Type Declarations
-----------------




```
/**
 * Debounce execution of a function.
 *
 * @see https://vueuse.org/useDebounceFn
 * @param  fn          A function to be executed after delay milliseconds debounced.
 * @param  ms          A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
 * @param  opts        options
 *
 * @return A new, debounce, function.
 */
export declare function useDebounceFn<T extends FunctionArgs>(
  fn: T,
  ms?: MaybeRefOrGetter<number>,
  options?: DebounceFilterOptions
): PromisifyFn<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useDebounceFn/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useDebounceFn/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useDebounceFn/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useDebounceFn/>

makeDestructurable
==================




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 364 B |
|  Last Changed  | 8 months ago |


Make isomorphic destructurable for object and array at the same time. See [this blog](https://antfu.me/posts/destructuring-with-object-or-array/) for more details.


Usage
-----


TypeScript Example:




```
import { makeDestructurable } from '@vueuse/core'

const foo = { name: 'foo' }
const bar = 1024

const obj = makeDestructurable(
  { foo, bar } as const,
  [ foo, bar ] as const,
)
```


Usage:




```
let { foo, bar } = obj
let [ foo, bar ] = obj
```


Type Declarations
-----------------




```
export declare function makeDestructurable<
  T extends Record<string, unknown>,
  A extends readonly any[]
>(obj: T, arr: A): T & A
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/makeDestructurable/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/makeDestructurable/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/makeDestructurable/>

useArrayIncludes
================




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 348 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.includes`


Usage
-----


### Use with reactive array




```
import { useArrayIncludes } from '@vueuse/core'

const list = ref([0, 2, 4, 6, 8])
const result = useArrayIncludes(list, 10)
// result.value: false
list.value.push(10)
// result.value: true
list.value.pop()
// result.value: false
```


Type Declarations
-----------------




```
export type UseArrayIncludesComparatorFn<T, V> = (
  element: T,
  value: V,
  index: number,
  array: MaybeRefOrGetter<T>[]
) => boolean
export interface UseArrayIncludesOptions<T, V> {
  fromIndex?: number
  comparator?: UseArrayIncludesComparatorFn<T, V> | keyof T
}
export declare function useArrayIncludes<T, V = any>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  value: MaybeRefOrGetter<V>,
  comparator?: UseArrayIncludesComparatorFn<T, V>
): ComputedRef<boolean>
export declare function useArrayIncludes<T, V = any>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  value: MaybeRefOrGetter<V>,
  comparator?: keyof T
): ComputedRef<boolean>
export declare function useArrayIncludes<T, V = any>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  value: MaybeRefOrGetter<V>,
  options?: UseArrayIncludesOptions<T, V>
): ComputedRef<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayIncludes/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayIncludes/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayIncludes/>

useIntervalFn
=============




|  |  |
| --- | --- |
|  Category  | [Animation](../../functions#category=Animation) |
|  Export Size  | 341 B |
|  Last Changed  | last week |


Wrapper for `setInterval` with controls


Usage
-----




```
import { useIntervalFn } from '@vueuse/core'

const { pause, resume, isActive } = useIntervalFn(() => {
  /* your function */
}, 1000)
```


Type Declarations
-----------------




```
export interface UseIntervalFnOptions {
  /**
   * Start the timer immediately
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Execute the callback immediate after calling this function
   *
   * @default false
   */
  immediateCallback?: boolean
}
/**
 * Wrapper for `setInterval` with controls
 *
 * @param cb
 * @param interval
 * @param options
 */
export declare function useIntervalFn(
  cb: Fn,
  interval?: MaybeRefOrGetter<number>,
  options?: UseIntervalFnOptions
): Pausable
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useIntervalFn/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useIntervalFn/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useIntervalFn/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useIntervalFn/>

watchDeep
=========




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 325 B |
|  Last Changed  | 4 days ago |


Shorthand for watching value with


Usage
-----


Similar to `watch`, but with `{ deep: true }`




```
import { watchDeep } from '@vueuse/core'

const nestedObject = ref({ foo: { bar: { deep: 5 } } })

watchDeep(nestedObject, (obj) => {
  console.log(updated)
})

onMounted(() => {
  nestedObject.value.foo.bar.deep = 10
})
```


Type Declarations
-----------------




```
export declare function watchDeep<
  T extends Readonly<MultiWatchSources>,
  Immediate extends Readonly<boolean> = false
>(
  source: T,
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options?: Omit<WatchOptions<Immediate>, "deep">
): WatchStopHandle
export declare function watchDeep<
  T,
  Immediate extends Readonly<boolean> = false
>(
  source: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: Omit<WatchOptions<Immediate>, "deep">
): WatchStopHandle
export declare function watchDeep<
  T extends object,
  Immediate extends Readonly<boolean> = false
>(
  source: T,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: Omit<WatchOptions<Immediate>, "deep">
): WatchStopHandle
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchDeep/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchDeep/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchDeep/>

watchImmediate
==============




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 322 B |
|  Last Changed  | 4 days ago |


Shorthand for watching value with


Usage
-----


Similar to `watch`, but with `{ immediate: true }`




```
import { watchImmediate } from '@vueuse/core'

const obj = ref('vue-use')

// changing the value from some external store/composables
obj.value = 'VueUse'

watchImmediate(nestedObject, (obj) => {
  console.log(updated) // Console.log will be logged twice
})
```


Type Declarations
-----------------




```
export declare function watchImmediate<T extends Readonly<MultiWatchSources>>(
  source: T,
  cb: WatchCallback<MapSources<T>, MapOldSources<T, true>>,
  options?: Omit<WatchOptions<true>, "deep">
): WatchStopHandle
export declare function watchImmediate<T>(
  source: WatchSource<T>,
  cb: WatchCallback<T, T | undefined>,
  options?: Omit<WatchOptions<true>, "deep">
): WatchStopHandle
export declare function watchImmediate<T extends object>(
  source: T,
  cb: WatchCallback<T, T | undefined>,
  options?: Omit<WatchOptions<true>, "deep">
): WatchStopHandle
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchImmediate/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchImmediate/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchImmediate/>

reactifyObject
==============




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 305 B |
|  Last Changed  | last month |


Apply [`reactify`](../reactify/index) to an object


Usage
-----




```
import { reactifyObject } from '@vueuse/core'

const reactifiedConsole = reactifyObject(console)

const a = ref('42')

reactifiedConsole.log(a) // no longer need `.value`
```


Type Declarations
-----------------




```
export type ReactifyNested<
  T,
  Keys extends keyof T = keyof T,
  S extends boolean = true
> = {
  [K in Keys]: T[K] extends AnyFn ? Reactified<T[K], S> : T[K]
}
export interface ReactifyObjectOptions<T extends boolean>
  extends ReactifyOptions<T> {
  /**
   * Includes names from Object.getOwnPropertyNames
   *
   * @default true
   */
  includeOwnProperties?: boolean
}
/**
 * Apply `reactify` to an object
 */
export declare function reactifyObject<T extends object, Keys extends keyof T>(
  obj: T,
  keys?: (keyof T)[]
): ReactifyNested<T, Keys, true>
export declare function reactifyObject<
  T extends object,
  S extends boolean = true
>(obj: T, options?: ReactifyObjectOptions<S>): ReactifyNested<T, keyof T, S>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactifyObject/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactifyObject/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/reactifyObject/>

useTimeoutFn
============




|  |  |
| --- | --- |
|  Category  | [Animation](../../functions#category=Animation) |
|  Export Size  | 303 B |
|  Last Changed  | 2 weeks ago |


Wrapper for `setTimeout` with controls.


Usage
-----




```
import { useTimeoutFn } from '@vueuse/core'

const { isPending, start, stop } = useTimeoutFn(() => {
  /* ... */
}, 3000)
```


Type Declarations
-----------------




```
export interface UseTimeoutFnOptions {
  /**
   * Start the timer immediate after calling this function
   *
   * @default true
   */
  immediate?: boolean
}
/**
 * Wrapper for `setTimeout` with controls.
 *
 * @param cb
 * @param interval
 * @param options
 */
export declare function useTimeoutFn<CallbackFn extends AnyFn>(
  cb: CallbackFn,
  interval: MaybeRefOrGetter<number>,
  options?: UseTimeoutFnOptions
): Stoppable<Parameters<CallbackFn> | []>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useTimeoutFn/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useTimeoutFn/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useTimeoutFn/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useTimeoutFn/>

extendRef
=========




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 282 B |
|  Last Changed  | last week |


Add extra attributes to Ref.



**WARNING**This function only works for Vue 2.7 or above.



Usage
-----



> Please note the extra attribute will not be accessible in Vue's template.
> 
> 




```
import { ref } from 'vue'
import { extendRef } from '@vueuse/core'

const myRef = ref('content')

const extended = extendRef(myRef, { foo: 'extra data' })

extended.value === 'content'
extended.foo === 'extra data'
```


Refs will be unwrapped and be reactive




```
const myRef = ref('content')
const extraRef = ref('extra')

const extended = extendRef(myRef, { extra: extraRef })

extended.value === 'content'
extended.extra === 'extra'

extended.extra = 'new data' // will trigger update
extraRef.value === 'new data'
```


Type Declarations
-----------------




```
export interface ExtendRefOptions<Unwrap extends boolean = boolean> {
  /**
   * Is the extends properties enumerable
   *
   * @default false
   */
  enumerable?: boolean
  /**
   * Unwrap for Ref properties
   *
   * @default true
   */
  unwrap?: Unwrap
}
/**
 * Overload 1: Unwrap set to false
 */
export declare function extendRef<
  R extends Ref<any>,
  Extend extends object,
  Options extends ExtendRefOptions<false>
>(ref: R, extend: Extend, options?: Options): ShallowUnwrapRef<Extend> & R
/**
 * Overload 2: Unwrap unset or set to true
 */
export declare function extendRef<
  R extends Ref<any>,
  Extend extends object,
  Options extends ExtendRefOptions
>(ref: R, extend: Extend, options?: Options): Extend & R
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/extendRef/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/extendRef/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/extendRef/>

watchArray
==========




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 281 B |
|  Last Changed  | 2 weeks ago |


Watch for an array with additions and removals.


Usage
-----


Similar to `watch`, but provides the added and removed elements to the callback function. Pass `{ deep: true }` if the list is updated in place with `push`, `splice`, etc.




```
import { watchArray } from '@vueuse/core'

const list = ref([1, 2, 3])

watchArray(list, (newList, oldList, added, removed) => {
  console.log(newList) // [1, 2, 3, 4]
  console.log(oldList) // [1, 2, 3]
  console.log(added) // [4]
  console.log(removed) // []
})

onMounted(() => {
  list.value = [...list.value, 4]
})
```


Type Declarations
-----------------




```
export declare type WatchArrayCallback<V = any, OV = any> = (
  value: V,
  oldValue: OV,
  added: V,
  removed: OV,
  onCleanup: (cleanupFn: () => void) => void
) => any
/**
 * Watch for an array with additions and removals.
 *
 * @see https://vueuse.org/watchArray
 */
export declare function watchArray<
  T,
  Immediate extends Readonly<boolean> = false
>(
  source: WatchSource<T[]> | T[],
  cb: WatchArrayCallback<T[], Immediate extends true ? T[] | undefined : T[]>,
  options?: WatchOptions<Immediate>
): WatchStopHandle
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchArray/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchArray/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchArray/>

toReactive
==========




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 242 B |
|  Last Changed  | 2 weeks ago |


Converts ref to reactive. Also made possible to create a "swapable" reactive object.



 **This function uses [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)** It is **NOT** supported by [IE 11 or below](https://caniuse.com/proxy). 



Usage
-----




```
import { toReactive } from '@vueuse/core'

const refState = ref({ foo: 'bar' })

console.log(refState.value.foo) // => 'bar'

const state = toReactive(refState) // <--

console.log(state.foo) // => 'bar'

refState.value = { bar: 'foo' }

console.log(state.foo) // => undefined
console.log(state.bar) // => 'foo'
```


Type Declarations
-----------------




```
/**
 * Converts ref to reactive.
 *
 * @see https://vueuse.org/toReactive
 * @param objectRef A ref of object
 */
export declare function toReactive<T extends object>(objectRef: MaybeRef<T>): T
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/toReactive/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/toReactive/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/toReactive/>

computedWithControl
===================




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 250 B |
|  Last Changed  | last week |
|  Alias  | `controlledComputed` |
|  Related  | [`refWithControl`](../refwithcontrol/index) |


Explicitly define the dependencies of computed.


Usage
-----




```
import { computedWithControl } from '@vueuse/core'

const source = ref('foo')
const counter = ref(0)

const computedRef = computedWithControl(
  () => source.value, // watch source, same as `watch`
  () => counter.value, // computed getter, same as `computed`
)
```


With this, the changes of `counter` won't trigger `computedRef` to update but the `source` ref does.




```
console.log(computedRef.value) // 0

counter.value += 1

console.log(computedRef.value) // 0

source.value = 'bar'

console.log(computedRef.value) // 1
```


### Manual Triggering


You can also manually trigger the update of the computed by:




```
const computedRef = computedWithControl(
  () => source.value,
  () => counter.value,
)

computedRef.trigger()
```



**WARNING**Manual triggering only works for Vue 3



Type Declarations
-----------------




```
export interface ComputedWithControlRefExtra {
  /**
   * Force update the computed value.
   */
  trigger(): void
}
export interface ComputedRefWithControl<T>
  extends ComputedRef<T>,
    ComputedWithControlRefExtra {}
export interface WritableComputedRefWithControl<T>
  extends WritableComputedRef<T>,
    ComputedWithControlRefExtra {}
export declare function computedWithControl<T, S>(
  source: WatchSource<S> | WatchSource<S>[],
  fn: ComputedGetter<T>
): ComputedRefWithControl<T>
export declare function computedWithControl<T, S>(
  source: WatchSource<S> | WatchSource<S>[],
  fn: WritableComputedOptions<T>
): WritableComputedRefWithControl<T>
export { computedWithControl as controlledComputed }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/computedWithControl/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/computedWithControl/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/computedWithControl/>

refAutoReset
============




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 234 B |
|  Last Changed  | 2 weeks ago |
|  Alias  | `autoResetRef` |


A ref which will be reset to the default value after some time.


Usage
-----




```
import { refAutoReset } from '@vueuse/core'

const message = refAutoReset('default message', 1000)

function setMessage() {
  // here the value will change to 'message has set' but after 1000ms, it will change to 'default message'
  message.value = 'message has set'
}
```


Type Declarations
-----------------




```
/**
 * Create a ref which will be reset to the default value after some time.
 *
 * @see https://vueuse.org/refAutoReset
 * @param defaultValue The value which will be set.
 * @param afterMs      A zero-or-greater delay in milliseconds.
 */
export declare function refAutoReset<T>(
  defaultValue: T,
  afterMs?: MaybeRefOrGetter<number>
): Ref<T>
export { refAutoReset as autoResetRef }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/refAutoReset/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/refAutoReset/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/refAutoReset/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/refAutoReset/>

useArrayDifference
==================




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 231 B |
|  Last Changed  | last week |


Reactive get array difference of two array


Usage
-----


### Use with reactive array




```
import { useArrayDifference } from '@vueuse/core'

const list1 = ref([0, 1, 2, 3, 4, 5])
const list2 = ref([4, 5, 6])
const result = useArrayDifference(list1, list2)
// result.value: [0, 1, 2, 3]
list2.value = [0, 1, 2]
// result.value: [3, 4, 5]
```


### Use with reactive array and use function comparison




```
import { useArrayDifference } from '@vueuse/core'

const list1 = ref([{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }])
const list2 = ref([{ id: 4 }, { id: 5 }, { id: 6 }])

const result = useArrayDifference(list1, list2, (value, othVal) => value.id === othVal.id)
// result.value: [{ id: 1 }, { id: 2 }, { id: 3 }]
```


Type Declarations
-----------------




```
export declare function useArrayDifference<T>(
  list: MaybeRefOrGetter<T[]>,
  values: MaybeRefOrGetter<T[]>,
  key?: keyof T
): ComputedRef<T[]>
export declare function useArrayDifference<T>(
  list: MaybeRefOrGetter<T[]>,
  values: MaybeRefOrGetter<T[]>,
  compareFn?: (value: T, othVal: T) => boolean
): ComputedRef<T[]>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayDifference/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayDifference/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayDifference/>

reactify
========




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 174 B |
|  Last Changed  | 2 weeks ago |
|  Alias  | `createReactiveFn` |
|  Related  | [`createUnrefFn`](../../core/createunreffn/index) |


Converts plain functions into reactive functions. The converted function accepts refs as its arguments and returns a ComputedRef, with proper typing.



**TIP**Interested to see some application or looking for some pre-reactified functions?


Check out [⚗️ Vue Chemistry](https://github.com/antfu/vue-chemistry)!



Usage
-----


Basic example




```
import { reactify } from '@vueuse/core'

// a plain function
function add(a: number, b: number): number {
  return a + b
}

// now it accept refs and returns a computed ref
// (a: number | Ref<number>, b: number | Ref<number>) => ComputedRef<number>
const reactiveAdd = reactify(add)

const a = ref(1)
const b = ref(2)
const sum = reactiveAdd(a, b)

console.log(sum.value) // 3

a.value = 5

console.log(sum.value) // 7
```


An example of implementing a reactive [Pythagorean theorem](https://en.wikipedia.org/wiki/Pythagorean_theorem).




```
import { reactify } from '@vueuse/core'

const pow = reactify(Math.pow)
const sqrt = reactify(Math.sqrt)
const add = reactify((a: number, b: number) => a + b)

const a = ref(3)
const b = ref(4)
const c = sqrt(add(pow(a, 2), pow(b, 2)))
console.log(c.value) // 5

// 5:12:13
a.value = 5
b.value = 12
console.log(c.value) // 13
```


You can also do it this way:




```
import { reactify } from '@vueuse/core'

function pythagorean(a: number, b: number) {
  return Math.sqrt(a ** 2 + b ** 2)
}

const a = ref(3)
const b = ref(4)

const c = reactify(pythagorean)(a, b)
console.log(c.value) // 5
```


Another example of making reactive `stringify`




```
import { reactify } from '@vueuse/core'

const stringify = reactify(JSON.stringify)

const obj = ref(42)
const dumped = stringify(obj)

console.log(dumped.value) // '42'

obj.value = { foo: 'bar' }

console.log(dumped.value) // '{"foo":"bar"}'
```


Type Declarations
-----------------




```
export type Reactified<T, Computed extends boolean> = T extends (
  ...args: infer A
) => infer R
  ? (
      ...args: {
        [K in keyof A]: Computed extends true
          ? MaybeRefOrGetter<A[K]>
          : MaybeRef<A[K]>
      }
    ) => ComputedRef<R>
  : never
export interface ReactifyOptions<T extends boolean> {
  /**
   * Accept passing a function as a reactive getter
   *
   * @default true
   */
  computedGetter?: T
}
/**
 * Converts plain function into a reactive function.
 * The converted function accepts refs as it's arguments
 * and returns a ComputedRef, with proper typing.
 *
 * @param fn - Source function
 */
export declare function reactify<T extends Function, K extends boolean = true>(
  fn: T,
  options?: ReactifyOptions<K>
): Reactified<T, K>
export { reactify as createReactiveFn }
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactify/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactify/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/reactify/>

reactiveComputed
================




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 264 B |
|  Last Changed  | last year |


Computed reactive object. Instead of returning a ref that `computed` does, [`reactiveComputed`](index) returns a reactive object.



 **This function uses [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)** It is **NOT** supported by [IE 11 or below](https://caniuse.com/proxy). 



Usage
-----




```
import { reactiveComputed } from '@vueuse/core'

const state = reactiveComputed(() => {
  return {
    foo: 'bar',
    bar: 'baz',
  }
})

state.bar // 'baz'
```


Type Declarations
-----------------




```
/**
 * Computed reactive object.
 */
export declare function reactiveComputed<T extends {}>(fn: () => T): T
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactiveComputed/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/reactiveComputed/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/reactiveComputed/>

createSharedComposable
======================




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 213 B |
|  Last Changed  | last month |
|  Related  | [`createGlobalState`](../createglobalstate/index) |


Make a composable function usable with multiple Vue instances.


Usage
-----




```
import { createSharedComposable, useMouse } from '@vueuse/core'

const useSharedMouse = createSharedComposable(useMouse)

// CompA.vue
const { x, y } = useSharedMouse()

// CompB.vue - will reuse the previous state and no new event listeners will be registered
const { x, y } = useSharedMouse()
```


Type Declarations
-----------------




```
/**
 * Make a composable function usable with multiple Vue instances.
 *
 * @see https://vueuse.org/createSharedComposable
 */
export declare function createSharedComposable<Fn extends AnyFn>(
  composable: Fn
): Fn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/createSharedComposable/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/createSharedComposable/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/createSharedComposable/>

useToNumber
===========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 200 B |
|  Last Changed  | 2 weeks ago |


Reactively convert a string ref to number.


Usage
-----




```
import { useToNumber } from '@vueuse/core'

const str = ref('123')
const number = useToNumber(str)

number.value // 123
```


Type Declarations
-----------------




```
export interface UseToNumberOptions {
  /**
   * Method to use to convert the value to a number.
   *
   * @default 'parseFloat'
   */
  method?: "parseFloat" | "parseInt"
  /**
   * The base in mathematical numeral systems passed to `parseInt`.
   * Only works with `method: 'parseInt'`
   */
  radix?: number
  /**
   * Replace NaN with zero
   *
   * @default false
   */
  nanToZero?: boolean
}
/**
 * Computed reactive object.
 */
export declare function useToNumber(
  value: MaybeRefOrGetter<number | string>,
  options?: UseToNumberOptions
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useToNumber/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useToNumber/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useToNumber/>

useToggle
=========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 200 B |
|  Last Changed  | 6 days ago |


A boolean switcher with utility functions.


Usage
-----




```
import { useToggle } from '@vueuse/core'

const [value, toggle] = useToggle()
```


When you pass a ref, [`useToggle`](index) will return a simple toggle function instead:




```
import { useDark, useToggle } from '@vueuse/core'

const isDark = useDark()
const toggleDark = useToggle(isDark)
```


Note: be aware that the toggle function accepts the first argument as the override value. You might want to avoid directly passing the function to events in the template, as the event object will pass in.




```
<!-- caution: $event will be pass in -->
<button @click="toggleDark" />
<!-- recommended to do this -->
<button @click="toggleDark()" />
```


Type Declarations
-----------------




```
export interface UseToggleOptions<Truthy, Falsy> {
  truthyValue?: MaybeRefOrGetter<Truthy>
  falsyValue?: MaybeRefOrGetter<Falsy>
}
export declare function useToggle<Truthy, Falsy, T = Truthy | Falsy>(
  initialValue: Ref<T>,
  options?: UseToggleOptions<Truthy, Falsy>
): (value?: T) => T
export declare function useToggle<
  Truthy = true,
  Falsy = false,
  T = Truthy | Falsy
>(
  initialValue?: T,
  options?: UseToggleOptions<Truthy, Falsy>
): [Ref<T>, (value?: T) => T]
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useToggle/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useToggle/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useToggle/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useToggle/>

useArrayUnique
==============




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 215 B |
|  Last Changed  | 2 weeks ago |


reactive unique array


Usage
-----


### Use with array of multiple refs




```
import { useArrayUnique } from '@vueuse/core'

const item1 = ref(0)
const item2 = ref(1)
const item3 = ref(1)
const item4 = ref(2)
const item5 = ref(3)
const list = [item1, item2, item3, item4, item5]
const result = useArrayUnique(list)
// result.value: [0, 1, 2, 3]
item5.value = 1
// result.value: [0, 1, 2]
```


### Use with reactive array




```
import { useArrayUnique } from '@vueuse/core'

const list = reactive([1, 2, 2, 3])
const result = useArrayUnique(list)
// result.value: [1, 2, 3]

list.push(1)
// result.value: [1, 2, 3]
```


### Use with custom function




```
import { useArrayUnique } from '@vueuse/core'

const list = reactive([
  { id: 1, name: 'foo' },
  { id: 2, name: 'bar' },
  { id: 1, name: 'baz' },
])

const result = useArrayUnique(list, (a, b) => a.id === b.id)
// result.value: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }]

list.push({ id: 1, name: 'qux' })
// result.value: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }]
```


Type Declarations
-----------------




```
/**
 * reactive unique array
 * @see https://vueuse.org/useArrayUnique
 * @param {Array} list - the array was called upon.
 * @param compareFn
 * @returns {Array} A computed ref that returns a unique array of items.
 */
export declare function useArrayUnique<T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  compareFn?: (a: T, b: T, array: T[]) => boolean
): ComputedRef<T[]>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayUnique/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayUnique/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayUnique/>

createEventHook
===============




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 212 B |
|  Last Changed  | 2 months ago |


Utility for creating event hooks


Usage
-----


Creating a function that uses `createEventHook`




```
import { createEventHook } from '@vueuse/core'

export function useMyFetch(url) {
  const fetchResult = createEventHook<Response>()
  const fetchError = createEventHook<any>()

  fetch(url)
    .then(result => fetchResult.trigger(result))
    .catch(error => fetchError.trigger(error.message))

  return {
    onResult: fetchResult.on,
    onError: fetchError.on,
  }
}
```


Using a function that uses `createEventHook`




```
<script setup lang="ts">
import { useMyFetch } from './my-fetch-function'

const { onResult, onError } = useMyFetch('my api url')

onResult((result) => {
  console.log(result)
})

onError((error) => {
  console.error(error)
})
</script>
```


Type Declarations
-----------------




```
export type EventHookOn<T = any> = (fn: (param: T) => void) => {
  off: () => void
}
export type EventHookOff<T = any> = (fn: (param: T) => void) => void
export type EventHookTrigger<T = any> = (param: T) => Promise<unknown[]>
export interface EventHook<T = any> {
  on: EventHookOn<T>
  off: EventHookOff<T>
  trigger: EventHookTrigger<T>
}
/**
 * Utility for creating event hooks
 *
 * @see https://vueuse.org/createEventHook
 */
export declare function createEventHook<T = any>(): EventHook<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/createEventHook/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/createEventHook/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/createEventHook/>

set
===




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 142 B |
|  Last Changed  | last year |


Shorthand for `ref.value = x`


Usage
-----




```
import { set } from '@vueuse/core'

const a = ref(0)

set(a, 1)

console.log(a.value) // 1
```


Type Declarations
-----------------




```
export declare function set<T>(ref: Ref<T>, value: T): void
export declare function set<O extends object, K extends keyof O>(
  target: O,
  key: K,
  value: O[K]
): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/set/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/set/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/set/>

useCounter
==========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 185 B |
|  Last Changed  | 6 months ago |


Basic counter with utility functions.


Basic Usage
-----------




```
import { useCounter } from '@vueuse/core'

const { count, inc, dec, set, reset } = useCounter()
```


Usage with options
------------------




```
import { useCounter } from '@vueuse/core'

const { count, inc, dec, set, reset } = useCounter(1, { min: 0, max: 16 })
```


Type Declarations
-----------------




```
export interface UseCounterOptions {
  min?: number
  max?: number
}
/**
 * Basic counter with utility functions.
 *
 * @see https://vueuse.org/useCounter
 * @param [initialValue=0]
 * @param {Object} options
 */
export declare function useCounter(
  initialValue?: number,
  options?: UseCounterOptions
): {
  count: Ref<number>
  inc: (delta?: number) => number
  dec: (delta?: number) => number
  get: () => number
  set: (val: number) => number
  reset: (val?: number) => number
}
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useCounter/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useCounter/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useCounter/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useCounter/>

useLastChanged
==============




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 143 B |
|  Last Changed  | last year |


Records the timestamp of the last change


Usage
-----




```
import { useLastChanged } from '@vueuse/core'

const a = ref(0)

const lastChanged = useLastChanged(a)

a.value = 1

console.log(lastChanged.value)
```


Type Declarations
-----------------




```
export interface UseLastChangedOptions<
  Immediate extends boolean,
  InitialValue extends number | null | undefined = undefined
> extends WatchOptions<Immediate> {
  initialValue?: InitialValue
}
/**
 * Records the timestamp of the last change
 *
 * @see https://vueuse.org/useLastChanged
 */
export declare function useLastChanged(
  source: WatchSource,
  options?: UseLastChangedOptions<false>
): Ref<number | null>
export declare function useLastChanged(
  source: WatchSource,
  options: UseLastChangedOptions<true>
): Ref<number>
export declare function useLastChanged(
  source: WatchSource,
  options: UseLastChangedOptions<boolean, number>
): Ref<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useLastChanged/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/useLastChanged/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useLastChanged/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useLastChanged/>

useArrayFindLast
================




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 191 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.findLast`.


Usage
-----




```
import { useArrayFindLast } from '@vueuse/core'

const list = [ref(1), ref(-1), ref(2)]
const positive = useArrayFindLast(list, val => val > 0)
// positive.value: 2
```


### Use with reactive array




```
import { useArrayFindLast } from '@vueuse/core'

const list = reactive([-1, -2])
const positive = useArrayFindLast(list, val => val > 0)
// positive.value: undefined
list.push(10)
// positive.value: 10
list.push(5)
// positive.value: 5
```


Type Declarations
-----------------




```
/**
 * Reactive `Array.findLast`
 *
 * @see https://vueuse.org/useArrayFindLast
 * @param {Array} list - the array was called upon.
 * @param fn - a function to test each element.
 *
 * @returns the last element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
 */
export declare function useArrayFindLast<T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  fn: (element: T, index: number, array: MaybeRefOrGetter<T>[]) => boolean
): ComputedRef<T | undefined>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayFindLast/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayFindLast/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayFindLast/>

toRef
=====




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 159 B |
|  Last Changed  | last week |
|  Alias  | `resolveRef` |
|  Related  | [`toValue`](../tovalue/index) |


Normalize value/ref/getter to `ref` or `computed`.


Usage
-----




```
import { toRef } from '@vueuse/core'

const foo = ref('hi')

const a = toRef(0) // Ref<number>
const b = toRef(foo) // Ref<string>
const c = toRef(() => 'hi') // ComputedRef<string>
```


Type Declarations
-----------------




```
/**
 * Normalize value/ref/getter to `ref` or `computed`.
 */
export declare function toRef<T>(r: () => T): Readonly<Ref<T>>
export declare function toRef<T>(r: ComputedRef<T>): ComputedRef<T>
export declare function toRef<T>(r: MaybeRefOrGetter<T>): Ref<T>
export declare function toRef<T>(r: T): Ref<T>
export declare function toRef<T extends object, K extends keyof T>(
  object: T,
  key: K
): ToRef<T[K]>
export declare function toRef<T extends object, K extends keyof T>(
  object: T,
  key: K,
  defaultValue: T[K]
): ToRef<Exclude<T[K], undefined>>
/**
 * @deprecated use `toRef` instead
 */
export declare const resolveRef: typeof toRef
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/toRef/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/toRef/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/toRef/>

useArrayEvery
=============




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 137 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.every`


Usage
-----


### Use with array of multiple refs




```
import { useArrayEvery } from '@vueuse/core'

const item1 = ref(0)
const item2 = ref(2)
const item3 = ref(4)
const item4 = ref(6)
const item5 = ref(8)
const list = [item1, item2, item3, item4, item5]
const result = useArrayEvery(list, i => i % 2 === 0)
// result.value: true
item1.value = 1
// result.value: false
```


### Use with reactive array




```
import { useArrayEvery } from '@vueuse/core'

const list = ref([0, 2, 4, 6, 8])
const result = useArrayEvery(list, i => i % 2 === 0)
// result.value: true
list.value.push(9)
// result.value: false
```


Type Declarations
-----------------




```
/**
 * Reactive `Array.every`
 *
 * @see https://vueuse.org/useArrayEvery
 * @param {Array} list - the array was called upon.
 * @param fn - a function to test each element.
 *
 * @returns {boolean} **true** if the `fn` function returns a **truthy** value for every element from the array. Otherwise, **false**.
 */
export declare function useArrayEvery<T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  fn: (element: T, index: number, array: MaybeRefOrGetter<T>[]) => unknown
): ComputedRef<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayEvery/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayEvery/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayEvery/>

useArrayReduce
==============




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 171 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.reduce`.


Usage
-----




```
import { useArrayReduce } from '@vueuse/core'

const sum = useArrayReduce([ref(1), ref(2), ref(3)], (sum, val) => sum + val)
// sum.value: 6
```


### Use with reactive array




```
import { useArrayReduce } from '@vueuse/core'

const list = reactive([1, 2])
const sum = useArrayReduce(list, (sum, val) => sum + val)

list.push(3)
// sum.value: 6
```


### Use with initialValue




```
import { useArrayReduce } from '@vueuse/core'

const list = reactive([{ num: 1 }, { num: 2 }])
const sum = useArrayReduce(list, (sum, val) => sum + val.num, 0)
// sum.value: 3
```


Type Declarations
-----------------



Show Type Declarations

```
export type UseArrayReducer<PV, CV, R> = (
  previousValue: PV,
  currentValue: CV,
  currentIndex: number
) => R
/**
 * Reactive `Array.reduce`
 *
 * @see https://vueuse.org/useArrayReduce
 * @param {Array} list - the array was called upon.
 * @param reducer - a "reducer" function.
 *
 * @returns the value that results from running the "reducer" callback function to completion over the entire array.
 */
export declare function useArrayReduce<T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  reducer: UseArrayReducer<T, T, T>
): ComputedRef<T>
/**
 * Reactive `Array.reduce`
 *
 * @see https://vueuse.org/useArrayReduce
 * @param {Array} list - the array was called upon.
 * @param reducer - a "reducer" function.
 * @param initialValue - a value to be initialized the first time when the callback is called.
 *
 * @returns the value that results from running the "reducer" callback function to completion over the entire array.
 */
export declare function useArrayReduce<T, U>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  reducer: UseArrayReducer<U, T, U>,
  initialValue: MaybeRefOrGetter<U>
): ComputedRef<U>
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayReduce/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayReduce/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayReduce/>

syncRefs
========




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 158 B |
|  Last Changed  | last year |
|  Related  | [`syncRef`](../syncref/index) |


Keep target refs in sync with a source ref


Usage
-----




```
import { syncRefs } from '@vueuse/core'

const source = ref('hello')
const target = ref('target')

const stop = syncRefs(source, target)

console.log(target.value) // hello

source.value = 'foo'

console.log(target.value) // foo
```


Watch options
-------------


The options for [`syncRefs`](index) are similar to `watch`'s `WatchOptions` but with different default values.




```
export interface SyncRefOptions {
  /**
   * Timing for syncing, same as watch's flush option
   *
   * @default 'sync'
   */
  flush?: WatchOptions['flush']
  /**
   * Watch deeply
   *
   * @default false
   */
  deep?: boolean
  /**
   * Sync values immediately
   *
   * @default true
   */
  immediate?: boolean
}
```


When setting `{ flush: 'pre' }`, the target reference will be updated at [the end of the current "tick"](https://vuejs.org/guide/essentials/watchers.html#callback-flush-timing) before rendering starts.




```
import { syncRefs } from '@vueuse/core'

const source = ref('hello')
const target = ref('target')

syncRefs(source, target, { flush: 'pre' })

console.log(target.value) // hello

source.value = 'foo'

console.log(target.value) // hello <- still unchanged, because of flush 'pre'

await nextTick()

console.log(target.value) // foo <- changed!
```


Type Declarations
-----------------




```
export interface SyncRefsOptions extends ConfigurableFlushSync {
  /**
   * Watch deeply
   *
   * @default false
   */
  deep?: boolean
  /**
   * Sync values immediately
   *
   * @default true
   */
  immediate?: boolean
}
/**
 * Keep target ref(s) in sync with the source ref
 *
 * @param source source ref
 * @param targets
 */
export declare function syncRefs<T>(
  source: WatchSource<T>,
  targets: Ref<T> | Ref<T>[],
  options?: SyncRefsOptions
): WatchStopHandle
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/syncRefs/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/syncRefs/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/syncRefs/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/syncRefs/>

useArrayFind
============




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 137 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.find`.


Usage
-----




```
import { useArrayFind } from '@vueuse/core'

const list = [ref(1), ref(-1), ref(2)]
const positive = useArrayFind(list, val => val > 0)
// positive.value: 1
```


### Use with reactive array




```
import { useArrayFind } from '@vueuse/core'

const list = reactive([-1, -2])
const positive = useArrayFind(list, val => val > 0)
// positive.value: undefined
list.push(1)
// positive.value: 1
```


Type Declarations
-----------------




```
/**
 * Reactive `Array.find`
 *
 * @see https://vueuse.org/useArrayFind
 * @param {Array} list - the array was called upon.
 * @param fn - a function to test each element.
 *
 * @returns the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
 */
export declare function useArrayFind<T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  fn: (element: T, index: number, array: MaybeRefOrGetter<T>[]) => boolean
): ComputedRef<T | undefined>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayFind/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayFind/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayFind/>

useArrayJoin
============




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 137 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.join`


Usage
-----


### Use with array of multiple refs




```
import { useArrayJoin } from '@vueuse/core'

const item1 = ref('foo')
const item2 = ref(0)
const item3 = ref({ prop: 'val' })
const list = [item1, item2, item3]
const result = useArrayJoin(list)
// result.value: foo,0,[object Object]
item1.value = 'bar'
// result.value: bar,0,[object Object]
```


### Use with reactive array




```
import { useArrayJoin } from '@vueuse/core'

const list = ref(['string', 0, { prop: 'val' }, false, [1], [[2]], null, undefined, []])
const result = useArrayJoin(list)
// result.value: string,0,[object Object],false,1,2,,,
list.value.push(true)
// result.value: string,0,[object Object],false,1,2,,,,true
list.value = [null, 'string', undefined]
// result.value: ,string,
```


### Use with reactive separator




```
import { useArrayJoin } from '@vueuse/core'

const list = ref(['string', 0, { prop: 'val' }])
const separator = ref()
const result = useArrayJoin(list, separator)
// result.value: string,0,[object Object]
separator.value = ''
// result.value: string0[object Object]
separator.value = '--'
// result.value: string--0--[object Object]
```


Type Declarations
-----------------




```
/**
 * Reactive `Array.join`
 *
 * @see https://vueuse.org/useArrayJoin
 * @param {Array} list - the array was called upon.
 * @param {string} separator - a string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (",").
 *
 * @returns {string} a string with all array elements joined. If arr.length is 0, the empty string is returned.
 */
export declare function useArrayJoin(
  list: MaybeRefOrGetter<MaybeRefOrGetter<any>[]>,
  separator?: MaybeRefOrGetter<string>
): ComputedRef<string>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayJoin/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayJoin/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayJoin/>

useArraySome
============




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 137 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.some`


Usage
-----


### Use with array of multiple refs




```
import { useArraySome } from '@vueuse/core'

const item1 = ref(0)
const item2 = ref(2)
const item3 = ref(4)
const item4 = ref(6)
const item5 = ref(8)
const list = [item1, item2, item3, item4, item5]
const result = useArraySome(list, i => i > 10)
// result.value: false
item1.value = 11
// result.value: true
```


### Use with reactive array




```
import { useArraySome } from '@vueuse/core'

const list = ref([0, 2, 4, 6, 8])
const result = useArraySome(list, i => i > 10)
// result.value: false
list.value.push(11)
// result.value: true
```


Type Declarations
-----------------




```
/**
 * Reactive `Array.some`
 *
 * @see https://vueuse.org/useArraySome
 * @param {Array} list - the array was called upon.
 * @param fn - a function to test each element.
 *
 * @returns {boolean} **true** if the `fn` function returns a **truthy** value for any element from the array. Otherwise, **false**.
 */
export declare function useArraySome<T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  fn: (element: T, index: number, array: MaybeRefOrGetter<T>[]) => unknown
): ComputedRef<boolean>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArraySome/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArraySome/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArraySome/>

useArrayMap
===========




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 133 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.map`


Usage
-----


### Use with array of multiple refs




```
import { useArrayMap } from '@vueuse/core'

const item1 = ref(0)
const item2 = ref(2)
const item3 = ref(4)
const item4 = ref(6)
const item5 = ref(8)
const list = [item1, item2, item3, item4, item5]
const result = useArrayMap(list, i => i * 2)
// result.value: [0, 4, 8, 12, 16]
item1.value = 1
// result.value: [2, 4, 8, 12, 16]
```


### Use with reactive array




```
import { useArrayMap } from '@vueuse/core'

const list = ref([0, 1, 2, 3, 4])
const result = useArrayMap(list, i => i * 2)
// result.value: [0, 2, 4, 6, 8]
list.value.pop()
// result.value: [0, 2, 4, 6]
```


Type Declarations
-----------------




```
/**
 * Reactive `Array.map`
 *
 * @see https://vueuse.org/useArrayMap
 * @param {Array} list - the array was called upon.
 * @param fn - a function that is called for every element of the given `list`. Each time `fn` executes, the returned value is added to the new array.
 *
 * @returns {Array} a new array with each element being the result of the callback function.
 */
export declare function useArrayMap<T, U = T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  fn: (element: T, index: number, array: T[]) => U
): ComputedRef<U[]>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayMap/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayMap/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayMap/>

createInjectionState
====================




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 132 B |
|  Last Changed  | 3 months ago |


Create global state that can be injected into components.


Usage
-----




```
// useCounterStore.ts
import { computed, ref } from 'vue'
import { createInjectionState } from '@vueuse/shared'

const [useProvideCounterStore, useCounterStore] = createInjectionState((initialValue: number) => {
  // state
  const count = ref(initialValue)

  // getters
  const double = computed(() => count.value * 2)

  // actions
  function increment() {
    count.value++
  }

  return { count, double, increment }
})

export { useProvideCounterStore }
// If you want to hide `useCounterStore` and wrap it in default value logic or throw error logic, please don't export `useCounterStore`
export { useCounterStore }

export function useCounterStoreWithDefaultValue() {
  return useCounterStore() ?? {
    count: ref(0),
    double: ref(0),
    increment: () => {},
  }
}

export function useCounterStoreOrThrow() {
  const counterStore = useCounterStore()
  if (counterStore == null)
    throw new Error('Please call `useProvideCounterStore` on the appropriate parent component')
  return counterStore
}
```




```
<!-- RootComponent.vue -->
<script setup lang="ts">
import { useProvideCounterStore } from './useCounterStore'

useProvideCounterStore(0)
</script>

<template>
  <div>
    <slot />
  </div>
</template>
```




```
<!-- CountComponent.vue -->
<script setup lang="ts">
import { useCounterStore } from './useCounterStore'

// use non-null assertion operator to ignore the case that store is not provided.
const { count, double } = useCounterStore()!
// if you want to allow component to working without providing store, you can use follow code instead:
// const { count, double } = useCounterStore() ?? { count: ref(0), double: ref(0) }
// also, you can use another hook to provide default value
// const { count, double } = useCounterStoreWithDefaultValue()
// or throw error
// const { count, double } = useCounterStoreOrThrow()
</script>

<template>
  <ul>
    <li>
      count: {{ count }}
    </li>
    <li>
      double: {{ double }}
    </li>
  </ul>
</template>
```




```
<!-- ButtonComponent.vue -->
<script setup lang="ts">
import { useCounterStore } from './useCounterStore'

// use non-null assertion operator to ignore the case that store is not provided.
const { increment } = useCounterStore()!
</script>

<template>
  <button @click="increment">
    +
  </button>
</template>
```


Type Declarations
-----------------




```
/**
 * Create global state that can be injected into components.
 *
 * @see https://vueuse.org/createInjectionState
 *
 */
export declare function createInjectionState<
  Arguments extends Array<any>,
  Return
>(
  composable: (...args: Arguments) => Return
): readonly [
  useProvidingState: (...args: Arguments) => Return,
  useInjectedState: () => Return | undefined
]
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/createInjectionState/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/createInjectionState/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/createInjectionState/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/createInjectionState/>

useArrayFindIndex
=================




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 136 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.findIndex`


Usage
-----


### Use with array of multiple refs




```
import { useArrayFindIndex } from '@vueuse/core'

const item1 = ref(0)
const item2 = ref(2)
const item3 = ref(4)
const item4 = ref(6)
const item5 = ref(8)
const list = [item1, item2, item3, item4, item5]
const result = useArrayFindIndex(list, i => i % 2 === 0)
// result.value: 0
item1.value = 1
// result.value: 1
```


### Use with reactive array




```
import { useArrayFindIndex } from '@vueuse/core'

const list = ref([0, 2, 4, 6, 8])
const result = useArrayFindIndex(list, i => i % 2 === 0)
// result.value: 0
list.value.unshift(-1)
// result.value: 1
```


Type Declarations
-----------------




```
/**
 * Reactive `Array.findIndex`
 *
 * @see https://vueuse.org/useArrayFindIndex
 * @param {Array} list - the array was called upon.
 * @param fn - a function to test each element.
 *
 * @returns {number} the index of the first element in the array that passes the test. Otherwise, "-1".
 */
export declare function useArrayFindIndex<T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  fn: (element: T, index: number, array: MaybeRefOrGetter<T>[]) => unknown
): ComputedRef<number>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayFindIndex/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayFindIndex/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayFindIndex/>

useArrayFilter
==============




|  |  |
| --- | --- |
|  Category  | [Array](../../functions#category=Array) |
|  Export Size  | 132 B |
|  Last Changed  | 2 weeks ago |


Reactive `Array.filter`


Usage
-----


### Use with array of multiple refs




```
import { useArrayFilter } from '@vueuse/core'

const item1 = ref(0)
const item2 = ref(2)
const item3 = ref(4)
const item4 = ref(6)
const item5 = ref(8)
const list = [item1, item2, item3, item4, item5]
const result = useArrayFilter(list, i => i % 2 === 0)
// result.value: [0, 2, 4, 6, 8]
item2.value = 1
// result.value: [0, 4, 6, 8]
```


### Use with reactive array




```
import { useArrayFilter } from '@vueuse/core'

const list = ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
const result = useArrayFilter(list, i => i % 2 === 0)
// result.value: [0, 2, 4, 6, 8]
list.value.shift()
// result.value: [2, 4, 6, 8]
```


Type Declarations
-----------------




```
/**
 * Reactive `Array.filter`
 *
 * @see https://vueuse.org/useArrayFilter
 * @param {Array} list - the array was called upon.
 * @param fn - a function that is called for every element of the given `list`. Each time `fn` executes, the returned value is added to the new array.
 *
 * @returns {Array} a shallow copy of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned.
 */
export declare function useArrayFilter<T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  fn: (element: T, index: number, array: T[]) => boolean
): ComputedRef<T[]>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayFilter/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useArrayFilter/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useArrayFilter/>

useToString
===========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 111 B |
|  Last Changed  | 2 weeks ago |


Reactively convert a ref to string.


Usage
-----




```
import { useToString } from '@vueuse/core'

const number = ref(3.14)
const str = useToString(number)

str.value // '3.14'
```


Type Declarations
-----------------




```
/**
 * Reactively convert a ref to string.
 *
 * @see https://vueuse.org/useToString
 */
export declare function useToString(
  value: MaybeRefOrGetter<unknown>
): ComputedRef<string>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/useToString/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/useToString/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/useToString/>

watchOnce
=========




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 107 B |
|  Last Changed  | 7 months ago |


`watch` that only triggers once.


Usage
-----


After the callback function has been triggered once, the watch will be stopped automatically.




```
import { watchOnce } from '@vueuse/core'

watchOnce(source, () => {
  // triggers only once
  console.log('source changed!')
})
```


Type Declarations
-----------------




```
export declare function watchOnce<
  T extends Readonly<WatchSource<unknown>[]>,
  Immediate extends Readonly<boolean> = false
>(
  source: [...T],
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options?: WatchOptions<Immediate>
): void
export declare function watchOnce<
  T,
  Immediate extends Readonly<boolean> = false
>(
  sources: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchOptions<Immediate>
): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchOnce/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/watchOnce/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/watchOnce/>

createGlobalState
=================




|  |  |
| --- | --- |
|  Category  | [State](../../functions#category=State) |
|  Export Size  | 125 B |
|  Last Changed  | last month |
|  Related  | [`createSharedComposable`](../createsharedcomposable/index) |


Keep states in the global scope to be reusable across Vue instances.


Usage
-----


### Without Persistence (Store in Memory)




```
// store.js
import { ref } from 'vue'
import { createGlobalState } from '@vueuse/core'

export const useGlobalState = createGlobalState(
  () => {
    const count = ref(0)
    return { count }
  }
)
```


A bigger example:




```
// store.js
import { computed, ref } from 'vue'
import { createGlobalState } from '@vueuse/core'

export const useGlobalState = createGlobalState(
  () => {
    // state
    const count = ref(0)

    // getters
    const doubleCount = computed(() => count.value * 2)

    // actions
    function increment() {
      count.value++
    }

    return { count, doubleCount, increment }
  }
)
```


### With Persistence


Store in `localStorage` with `useStorage()`:




```
// store.js
import { createGlobalState, useStorage } from '@vueuse/core'

export const useGlobalState = createGlobalState(
  () => useStorage('vueuse-local-storage', 'initialValue'),
)
```




```
// component.js
import { useGlobalState } from './store'

export default defineComponent({
  setup() {
    const state = useGlobalState()
    return { state }
  },
})
```


Type Declarations
-----------------




```
/**
 * Keep states in the global scope to be reusable across Vue instances.
 *
 * @see https://vueuse.org/createGlobalState
 * @param stateFactory A factory function to create the state
 */
export declare function createGlobalState<Fn extends AnyFn>(
  stateFactory: Fn
): Fn
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/createGlobalState/index.ts) • [Demo](https://github.com/vueuse/vueuse/blob/main/packages/shared/createGlobalState/demo.vue) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/createGlobalState/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/createGlobalState/>

tryOnBeforeMount
================




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 114 B |
|  Last Changed  | 10 months ago |


Safe `onBeforeMount`. Call `onBeforeMount()` if it's inside a component lifecycle, if not, just call the function


Usage
-----




```
import { tryOnBeforeMount } from '@vueuse/core'

tryOnBeforeMount(() => {

})
```


Type Declarations
-----------------




```
/**
 * Call onBeforeMount() if it's inside a component lifecycle, if not, just call the function
 *
 * @param fn
 * @param sync if set to false, it will run in the nextTick() of Vue
 */
export declare function tryOnBeforeMount(fn: Fn, sync?: boolean): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnBeforeMount/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnBeforeMount/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/tryOnBeforeMount/>

tryOnMounted
============




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 109 B |
|  Last Changed  | last year |


Safe `onMounted`. Call `onMounted()` if it's inside a component lifecycle, if not, just call the function


Usage
-----




```
import { tryOnMounted } from '@vueuse/core'

tryOnMounted(() => {

})
```


Type Declarations
-----------------




```
/**
 * Call onMounted() if it's inside a component lifecycle, if not, just call the function
 *
 * @param fn
 * @param sync if set to false, it will run in the nextTick() of Vue
 */
export declare function tryOnMounted(fn: Fn, sync?: boolean): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnMounted/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnMounted/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/tryOnMounted/>

get
===




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 80 B |
|  Last Changed  | 2 weeks ago |


Shorthand for accessing `ref.value`


Usage
-----




```
import { get } from '@vueuse/core'

const a = ref(42)

console.log(get(a)) // 42
```


Type Declarations
-----------------




```
/**
 * Shorthand for accessing `ref.value`
 */
export declare function get<T>(ref: MaybeRef<T>): T
export declare function get<T, K extends keyof T>(
  ref: MaybeRef<T>,
  key: K
): T[K]
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/get/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/get/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/get/>

whenever
========




|  |  |
| --- | --- |
|  Category  | [Watch](../../functions#category=Watch) |
|  Export Size  | 97 B |
|  Last Changed  | 9 months ago |


Shorthand for watching value to be truthy.


Usage
-----




```
import { useAsyncState, whenever } from '@vueuse/core'

const { state, isReady } = useAsyncState(
  fetch('https://jsonplaceholder.typicode.com/todos/1').then(t => t.json()),
  {},
)

whenever(isReady, () => console.log(state))
```




```
// this
whenever(ready, () => console.log(state))

// is equivalent to:
watch(ready, (isReady) => {
  if (isReady)
    console.log(state)

})
```


### Callback Function


Same as `watch`, the callback will be called with `cb(value, oldValue, onInvalidate)`.




```
whenever(height, (current, lastHeight) => {
  if (current > lastHeight)
    console.log(`Increasing height by ${current - lastHeight}`)

})
```


### Computed


Same as `watch`, you can pass a getter function to calculate on each change.




```
// this
whenever(
  () => counter.value === 7,
  () => console.log('counter is 7 now!'),
)
```


### Options


Options and defaults are same with `watch`.




```
// this
whenever(
  () => counter.value === 7,
  () => console.log('counter is 7 now!'),
  { flush: 'sync' },
)
```


Type Declarations
-----------------




```
/**
 * Shorthand for watching value to be truthy
 *
 * @see https://vueuse.org/whenever
 */
export declare function whenever<T>(
  source: WatchSource<T | false | null | undefined>,
  cb: WatchCallback<T>,
  options?: WatchOptions
): WatchStopHandle
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/whenever/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/whenever/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/whenever/>

tryOnScopeDispose
=================




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 100 B |
|  Last Changed  | 3 months ago |


Safe `onScopeDispose`. Call `onScopeDispose()` if it's inside an effect scope lifecycle, if not, do nothing


Usage
-----




```
import { tryOnScopeDispose } from '@vueuse/core'

tryOnScopeDispose(() => {

})
```


Type Declarations
-----------------




```
/**
 * Call onScopeDispose() if it's inside an effect scope lifecycle, if not, do nothing
 *
 * @param fn
 */
export declare function tryOnScopeDispose(fn: Fn): boolean
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnScopeDispose/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnScopeDispose/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/tryOnScopeDispose/>

tryOnBeforeUnmount
==================




|  |  |
| --- | --- |
|  Category  | [Component](../../functions#category=Component) |
|  Export Size  | 93 B |
|  Last Changed  | last year |


Safe `onBeforeUnmount`. Call `onBeforeUnmount()` if it's inside a component lifecycle, if not, do nothing


Usage
-----




```
import { tryOnBeforeUnmount } from '@vueuse/core'

tryOnBeforeUnmount(() => {

})
```


Type Declarations
-----------------




```
/**
 * Call onBeforeUnmount() if it's inside a component lifecycle, if not, do nothing
 *
 * @param fn
 */
export declare function tryOnBeforeUnmount(fn: Fn): void
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnBeforeUnmount/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnBeforeUnmount/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/tryOnBeforeUnmount/>

refDefault
==========




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 107 B |
|  Last Changed  | last year |


Apply default value to a ref.


Usage
-----




```
import { refDefault, useStorage } from '@vueuse/core'

const raw = useStorage('key')
const state = refDefault(raw, 'default')

raw.value = 'hello'
console.log(state.value) // hello

raw.value = undefined
console.log(state.value) // default
```


Type Declarations
-----------------




```
/**
 * Apply default value to a ref.
 *
 * @param source source ref
 * @param targets
 */
export declare function refDefault<T>(
  source: Ref<T | undefined | null>,
  defaultValue: T
): Ref<T>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/refDefault/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/refDefault/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/refDefault/>

toValue
=======




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 92 B |
|  Last Changed  | 2 weeks ago |
|  Alias  | `resolveUnref` |
|  Related  | [`toRef`](../toref/index) |


Get the value of value/ref/getter.


Usage
-----




```
import { toValue } from '@vueuse/core'

const foo = ref('hi')

const a = toValue(0) // 0
const b = toValue(foo) // 'hi'
const c = toValue(() => 'hi') // 'hi'
```


Type Declarations
-----------------




```
/**
 * Get the value of value/ref/getter.
 */
export declare function toValue<T>(r: MaybeRefOrGetter<T>): T
/**
 * @deprecated use `toValue` instead
 */
export declare const resolveUnref: typeof toValue
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/toValue/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/toValue/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/toValue/>

isDefined
=========




|  |  |
| --- | --- |
|  Category  | [Utilities](../../functions#category=Utilities) |
|  Export Size  | 86 B |
|  Last Changed  | 2 weeks ago |


Non-nullish checking type guard for Ref.


Usage
-----




```
import { isDefined } from '@vueuse/core'

const example = ref(Math.random() ? 'example' : undefined) // Ref<string | undefined>

if (isDefined(example))
  example // Ref<string>
```


Type Declarations
-----------------




```
export declare function isDefined<T>(
  v: Ref<T>
): v is Ref<Exclude<T, null | undefined>>
export declare function isDefined<T>(
  v: ComputedRef<T>
): v is ComputedRef<Exclude<T, null | undefined>>
export declare function isDefined<T>(v: T): v is Exclude<T, null | undefined>
```


Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/isDefined/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/isDefined/index.md)


*No recent changes*

 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/shared/isDefined/>

computedAsync
=============




|  |  |
| --- | --- |
|  Category  | [Reactivity](../../functions#category=Reactivity) |
|  Export Size  | 358 B |
|  Last Changed  | 2 months ago |
|  Alias  | `asyncComputed` |


Computed for async functions


Usage
-----




```
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.




```
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.




```
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.




```
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.


Type Declarations
-----------------



Show Type Declarations

```
/**
 * Handle overlapping async evaluations.
 *
 * @param cancelCallback The provided callback is invoked when a re-evaluation of the computed value is triggered before the previous one finished
 */
export type AsyncComputedOnCancel = (cancelCallback: Fn) => void
export interface AsyncComputedOptions {
  /**
   * Should value be evaluated lazily
   *
   * @default false
   */
  lazy?: boolean
  /**
   * Ref passed to receive the updated of async evaluation
   */
  evaluating?: Ref<boolean>
  /**
   * Use shallowRef
   *
   * @default true
   */
  shallow?: boolean
  /**
   * Callback when error is caught.
   */
  onError?: (e: unknown) => void
}
/**
 * Create an asynchronous computed dependency.
 *
 * @see https://vueuse.org/computedAsync
 * @param evaluationCallback     The promise-returning callback which generates the computed value
 * @param initialState           The initial state, used until the first evaluation finishes
 * @param optionsOrRef           Additional options or a ref passed to receive the updates of the async evaluation
 */
export declare function computedAsync<T>(
  evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,
  initialState?: T,
  optionsOrRef?: Ref<boolean> | AsyncComputedOptions
): Ref<T>
export { computedAsync as asyncComputed }
```



Source
------


[Source](https://github.com/vueuse/vueuse/blob/main/packages/core/computedAsync/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/core/computedAsync/index.md)



 © 2019-present Anthony Fu  
Licensed under the MIT License.  

<https://vueuse.org/core/computedAsync/>

vueuse