Files
escrcpy/context/vue-use.md
viarotel af405401c9 feat: 🚀 release v2.10.2 core edition
Escrcpy now focuses on a cleaner and more stable core architecture.
Advanced features are moved to the private repository EscrcpyX.
2026-05-13 11:41:57 +08:00

430 KiB
Raw Permalink Blame History

Setup and Development Commands

Source: https://vueuse.org/contributing

Commands for installing dependencies and starting the local development server.

pnpm install
pnpm dev

Setup and Usage of useAuth

Source: https://vueuse.org/firebase/useauth

Demonstrates how to initialize Firebase, get the auth instance, and use the useAuth composable to manage authentication state and user information. Includes a button to trigger Google Sign-In.

<script setup lang="ts">
import { 
useAuth
 } from '@vueuse/firebase/useAuth'
import { 
initializeApp
 } from 'firebase/app'
import { 
getAuth
,
GoogleAuthProvider
,
signInWithPopup
 } from 'firebase/auth'

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>

Installation

Source: https://vueuse.org/electron/README

Install the @vueuse/electron package along with electron itself.

## Install

```bash
npm i @vueuse/electron electron

--------------------------------

### useVModel with Options API

Source: https://vueuse.org/core/useVModel

This example shows how to use useVModel within the Options API setup function. It demonstrates accessing and updating the bound value.

```typescript
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')
  },
}


Basic Usage Example

Source: https://vueuse.org/core/useFileDialog

A simple example demonstrating how to use useFileDialog to open a file dialog for image files.

## Example: Basic File Dialog

### Description
This example shows how to use `useFileDialog` to open a file dialog that accepts only image files and logs the selected files.

### Code
```vue
<script setup lang="ts">
import { useFileDialog } from '@vueuse/core'

const { files, open, reset, onCancel, onChange } = useFileDialog({
  accept: 'image/*',
  directory: false, // Set to true to select directories
})

onChange((newFiles) => {
  if (newFiles) {
    console.log('Selected files:', newFiles)
    // Do something with the selected files
  }
})

onCancel(() => {
  console.log('File dialog cancelled')
  // Handle cancellation
})
</script>

<template>
  <button type="button" @click="open()">
    Choose Image File
  </button>
  <button type="button" @click="reset()" :disabled="!files">
    Reset Selection
  </button>

  <div v-if="files">
    <h3>Selected Files:</h3>
    <ul>
      <li v-for="file in files" :key="file.name">{{ file.name }} ({{ file.size }} bytes)</li>
    </ul>
  </div>
</template>

--------------------------------

### Buffer Input Example

Source: https://vueuse.org/core/useBase64

Example of a buffer input.

```text
new ArrayBuffer(1024)

Install useQRCode dependency

Source: https://vueuse.org/integrations/useQRCode

Install the required qrcode package before using the integration.

npm i qrcode@^1

Install @vueuse/math

Source: https://vueuse.org/math/readme

Use this command to install the math extension along with the core VueUse library.

npm i @vueuse/math @vueuse/core

Install Sortable.js

Source: https://vueuse.org/integrations/useSortable

Install the necessary Sortable.js library using npm.

npm i sortablejs@^1

Install @vueuse/rxjs

Source: https://vueuse.org/rxjs/readme

Install the package and its peer dependency using npm.

npm i @vueuse/rxjs rxjs

Usage Example

Source: https://vueuse.org/math/logicAnd

Example demonstrating how to use the logicAnd function with whenever.

## Usage Example

### Description
This example shows how to use `logicAnd` in conjunction with `whenever` to trigger a callback when multiple conditions become true.

### Method
N/A (Illustrative Example)

### Endpoint
N/A

### Parameters
N/A

### Request Example
```ts
import { ref, whenever } from '@vueuse/core'
import { logicAnd } from '@vueuse/math'

const a = ref(true)
const b = ref(false)

whenever(logicAnd(a, b), () => {
  console.log('both a and b are now truthy!')
})

// To make the console.log appear, you would need to set 'a.value = true' and 'b.value = true'

Response

N/A


--------------------------------

### Advanced Usage Example

Source: https://vueuse.org/core/useFileDialog

An example demonstrating advanced `useFileDialog` options like multiple file selection and initial files.

```APIDOC
## Example: Advanced File Dialog Options

### Description
This example demonstrates using `useFileDialog` with options for multiple file selection and setting initial files.

### Code
```vue
<script setup lang="ts">
import { ref } from 'vue'
import { useFileDialog } from '@vueuse/core'

const initialFileList = ref<File[]>([]) // Example: You might fetch this from an API

const { files, open, reset } = useFileDialog({
  multiple: true, // Allow multiple file selection
  accept: '.pdf, .doc, .docx',
  initialFiles: initialFileList.value, // Set initial files
  directory: false,
})

// You can also open with specific options overriding the initial ones
const openSpecific = () => {
  open({
    accept: 'text/plain',
    multiple: false,
  })
}
</script>

<template>
  <button type="button" @click="open()">
    Choose Documents (Multiple)
  </button>
  <button type="button" @click="openSpecific()">
    Choose Text File (Single)
  </button>
  <button type="button" @click="reset()" :disabled="!files">
    Reset Selection
  </button>

  <div v-if="files && files.length > 0">
    <h3>Selected Files:</h3>
    <ul>
      <li v-for="file in files" :key="file.name">{{ file.name }}</li>
    </ul>
  </div>
</template>

--------------------------------

### Install focus-trap

Source: https://vueuse.org/integrations/useFocusTrap

Install the focus-trap library, which is a peer dependency for useFocusTrap.

```bash
npm i focus-trap@^7

Install change-case

Source: https://vueuse.org/integrations/useChangeCase

Install the change-case package as a dependency.

npm i change-case@^5

Use useWindowSize in Vue Script Setup

Source: https://vueuse.org/core/useWindowSize

Import and use the useWindowSize composable in your Vue script setup to get reactive window width and height. No additional setup is required.

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

const { 
width
,
height
 } = 
useWindowSize
()
</script>

<template>
  <
div
>
    Width: {{ 
width
 }}
    Height: {{ 
height
 }}
  </
div
>
</template>

Install @vueuse/integrations

Source: https://vueuse.org/integrations/README

Install the @vueuse/integrations package using npm.

npm i @vueuse/integrations

Start and Preview Screen Share Stream

Source: https://vueuse.org/core/useDisplayMedia

Demonstrates how to use useDisplayMedia to start a screen share stream and preview it on a video element. Ensure the video element is correctly referenced using useTemplateRef.

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

const { 
stream
,
start
 } = 
useDisplayMedia
()

// start streaming

start
()

const 
videoRef
 = 
useTemplateRef
('video')

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

})
</script>

<template>
  <video 
ref
="
video
" />
</template>

Install @vueuse/core and @vueuse/components

Source: https://vueuse.org/guide/components

Install the necessary packages for using VueUse core functionalities and its component library.

npm i @vueuse/core @vueuse/components

Install NProgress

Source: https://vueuse.org/integrations/useNProgress

Install the required nprogress dependency.

npm i nprogress@^0

HTML Output for Custom Configuration

Source: https://vueuse.org/core/useDark

Shows the resulting HTML structure when using the custom configuration example.

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

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

Initialize and commit manual ref history

Source: https://vueuse.org/core/useManualRefHistory

Demonstrates basic setup using shallowRef and manual commit to record snapshots.

import { 
useManualRefHistory
 } from '@vueuse/core'
import { 
shallowRef
 } from 'vue'

const 
counter
 = 
shallowRef
(0)
const { 
history
, 
commit
, 
undo
, 
redo
 } = 
useManualRefHistory
(
counter
)


counter
.
value
 += 1

commit
()


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

Install VueUse Core

Source: https://vueuse.org/guide

Install the core package via npm.

npm i @vueuse/core

useVModels - Options API Usage

Source: https://vueuse.org/core/usevmodels

Illustrates how to integrate useVModels within Vue's Options API. This example shows how to access and modify props using useVModels within the setup function.

## useVModels - Options API

### Description
Usage of `useVModels` within the Options API.

### Method
Options API with `setup` function

### Endpoint
N/A (Composable function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
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')
  },
}

Response

Success Response (200)

Provides reactive references for props that can be manipulated within the Options API setup.

Response Example

{
  "foo": "",
  "bar": 0
}

--------------------------------

### Provide SSR Width - App Instance Example

Source: https://vueuse.org/core/useSSRWidth

Example of how to provide the SSR width when creating the Vue application instance.

```APIDOC
## Provide SSR Width - App Instance

### Description
This example demonstrates how to use `provideSSRWidth` when initializing your Vue application to set a global SSR viewport width.

### Method
`provideSSRWidth`

### Endpoint
N/A (Composable function)

### Parameters
- **width** (number) - The SSR viewport width (e.g., 500).
- **app** (App) - The Vue application instance.

### Request Example
```ts
import { createApp } from 'vue'
import App from './App.vue'
import { provideSSRWidth } from '@vueuse/core'

const app = createApp(App)

// Provide a global SSR width of 500px
provideSSRWidth(500, app)

app.mount('#app')

--------------------------------

### useSortable Return Values (TypeScript)

Source: https://vueuse.org/integrations/useSortable

TypeScript example demonstrating the usage of `start`, `stop`, and `option` functions returned by `useSortable` for controlling and querying the Sortable instance.

```typescript
const { 
start
,
stop
,
option
 } = useSortable(el, list)

// Stop sorting

stop
()

// Start sorting again

start
()

// Get/set options

option
('animation', 200) // set
const 
animation
 = 
option
('animation') // get

useNProgress with Progress Percentage

Source: https://vueuse.org/integrations/useNProgress

This example shows how to initialize and control the progress bar with a specific percentage.

## useNProgress with Progress Percentage

### Description
Initialize the progress bar to a specific percentage and manually set it to completion.

### Method
`useNProgress`

### Endpoint
N/A (Composable function)

### Parameters
- **currentProgress** (MaybeRefOrGetter<number | null | undefined>) - Optional. The initial progress percentage (0 to 1).

### Request Example
```typescript
import { useNProgress } from '@vueuse/integrations/useNProgress'

const { progress } = useNProgress(0.5)

function done() {
  progress.value = 1.0
}

Response

  • progress (Ref<number | null | undefined>) - A ref that holds the current progress percentage.

Response Example

{
  "progress": 1.0
}

--------------------------------

### Track Document Visibility in Script Setup

Source: https://vueuse.org/core/useDocumentVisibility

Import and use the `useDocumentVisibility` composable in your script setup to get a reactive reference to the document's visibility state. No additional setup is required.

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

const 
visibility
 = 
useDocumentVisibility
()
</script>

Install @vueuse/electron

Source: https://vueuse.org/electron/README

Install the @vueuse/electron package along with electron itself to use its features.

npm i @vueuse/electron electron

useSortable Return Values (JavaScript)

Source: https://vueuse.org/integrations/useSortable

JavaScript example illustrating how to use the start, stop, and option functions returned by useSortable to manage the Sortable.js instance.

'use strict'
const { start, stop, option } = useSortable(el, list)
// Stop sorting
stop()
// Start sorting again
start()
// Get/set options
option('animation', 200) // set
const animation = option('animation') // get

useFuse Usage Example

Source: https://vueuse.org/integrations/useFuse

A basic example demonstrating how to use the useFuse composable with a list of strings and a shallowRef for input.

## Usage

```ts
import { useFuse } from '@vueuse/integrations/useFuse'
import { shallowRef } from 'vue'

const data = [
  'John Smith',
  'John Doe',
  'Jane Doe',
  'Phillip Green',
  'Peter Brown',
]

const input = shallowRef('Jhon D')

const { results } = useFuse(input, data)

/*
 * Results:
 *
 * { "item": "John Doe", "index": 1 }
 * { "item": "John Smith", "index": 0 }
 * { "item": "Jane Doe", "index": 2 }
 *
 */

--------------------------------

### useTimeout with Controls

Source: https://vueuse.org/shared/useTimeout

This example shows how to use `useTimeout` with the `controls` option enabled, exposing `start`, `stop`, and `isPending` functions.

```APIDOC
## useTimeout with Controls

### Description

This example demonstrates using `useTimeout` with the `controls` option set to `true`. This exposes additional functions to manually control the timeout, such as starting, stopping, and checking its pending state.

### Method

`useTimeout`

### Parameters

#### Path Parameters

None

#### Query Parameters

None

#### Request Body

None

### Request Example

```ts
import { useTimeout } from '@vueuse/core'

const { ready, start, stop, isPending } = useTimeout(1000, { controls: true })

// Check if timeout is pending
console.log(isPending.value) // true

// Stop the timeout
stop()

// Start/restart the timeout
start()

Response

Success Response (200)

  • ready (ComputedRef) - A computed ref that becomes true after the timeout duration.
  • start (Function) - A function to start or restart the timeout.
  • stop (Function) - A function to stop the timeout.
  • isPending (ComputedRef) - A computed ref indicating if the timeout is currently active.

Response Example

{
  "ready": false,
  "isPending": true
}

--------------------------------

### Form state example

Source: https://vueuse.org/core/useStepper

Example of the form state object used in the wizard demo.

```json
{
  "firstName": "Jon",
  "lastName": "",
  "billingAddress": "",
  "contractAccepted": false,
  "carbonOffsetting": false,
  "payment": "credit-card"
}

Basic useSwipe Setup

Source: https://vueuse.org/core/useSwipe

Set up useSwipe to detect swipes on an element. Import useSwipe and useTemplateRef, then bind the element to the ref.

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

const 
el
 = 
useTemplateRef
('el')
const { 
isSwiping
, 
direction
 } = 
useSwipe
(
el
)
</script>

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


Basic usePointer Usage

Source: https://vueuse.org/core/usePointer

Import and use the usePointer function to get reactive references for pointer coordinates and pressure. No additional setup is required.

import {
usePointer
} from '@vueuse/core'

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

Source: https://vueuse.org/integrations/useCookies

Install the required dependency for useCookies.

npm i universal-cookie@^7

More Examples

Source: https://vueuse.org/shared/until

Provides various examples of using until with different matching conditions like toBe, toMatch, changed, toBeTruthy, toBeNull, and negation.

## More Examples

### Description
Illustrates various use cases for the `until` function, including checking for specific values, value changes, truthiness, nullity, and using negation.

### Method
`until(ref).toBe(true)`
`until(ref).toMatch(v => v > 10 && v < 100)`
`until(ref).changed()`
`until(ref).changedTimes(10)`
`until(ref).toBeTruthy()`
`until(ref).toBeNull()`
`until(ref).not.toBeNull()`
`until(ref).not.toBeTruthy()`

### Endpoint
N/A (Composition API function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
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()

Response

Success Response (200)

N/A (This is a client-side composition function)

Response Example

N/A


--------------------------------

### useCookies API

Source: https://vueuse.org/integrations/useCookies

This section details the useCookies composable, its installation, and various usage examples.

```APIDOC
## useCookies

### Description
Wrapper for `universal-cookie`. Provides a convenient way to access and modify cookies using Vue Composition API.

### Install
```bash
npm i universal-cookie@^7

Usage

Common Usage

<script setup lang="ts">
import { useCookies } from '@vueuse/integrations/useCookies'

const cookies = useCookies(['locale'])
</script>

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

Options

Access and modify cookies using vue composition-api.

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 toget/getAll methods.
  • autoUpdateDependencies (boolean = false): automatically add cookie names ever provided to get 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

createCookies([req])

Create a universal-cookie instance using request (default is window.document.cookie) and returns useCookies function with provided universal-cookie instance

  • req (object): Node's http.IncomingMessage request object

--------------------------------

### Configuring useAsyncState options

Source: https://vueuse.org/core/useAsyncState

Provides a comprehensive example of available configuration options for useAsyncState.

```ts
const { 
state
 } = useAsyncState(promise, initialState, {
  // Execute immediately on creation (default: true)
  
immediate
: true,
  // Delay before first execution in ms (default: 0)
  
delay
: 0,
  // Reset state to initial before each execution (default: true)
  
resetOnExecute
: true,
  // Use shallowRef for state (default: true)
  
shallow
: true,
  // Throw errors instead of catching them (default: false)
  
throwError
: false,
  // Called when promise resolves
  
onSuccess
(
data
) {
    
console
.
log
('Success:', 
data
)
  },
  // Called when promise rejects
  
onError
(
error
) {
    
console
.
error
('Error:', 
error
)
  },
})
'use strict'
const { state } = useAsyncState(promise, initialState, {
  // Execute immediately on creation (default: true)
  immediate: true,
  // Delay before first execution in ms (default: 0)
  delay: 0,
  // Reset state to initial before each execution (default: true)
  resetOnExecute: true,
  // Use shallowRef for state (default: true)
  shallow: true,
  // Throw errors instead of catching them (default: false)
  throwError: false,
  // Called when promise resolves
  onSuccess(data) {
    console.log('Success:', data)
  },
  // Called when promise rejects
  onError(error) {
    console.error('Error:', error)
  },
})

Basic useDropZone Setup

Source: https://vueuse.org/core/usedropzone

Set up a drop zone element and handle dropped files. Specify accepted data types and whether multiple files are allowed. The isOverDropZone ref indicates when the cursor is within the drop zone.

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

const 
dropZoneRef
 = 
useTemplateRef
('dropZoneRef')

function 
onDrop
(
files
: File[] | null) {
  // called when files are dropped on zone
}

const { 
isOverDropZone
 } = 
useDropZone
(
dropZoneRef
, {
  
onDrop
,
  // specify the types of data to be received.
  
dataTypes
: ['image/jpeg'],
  // control multi-file drop
  
multiple
: true,
  // whether to prevent default behavior for unhandled events
  
preventDefaultForUnhandled
: false,
})
</script>

<template>
  <
div
 
ref
="
dropZoneRef
">
    Drop files here
  </
div
>
</template>


Install Fuse.js

Source: https://vueuse.org/integrations/usefuse

Install the required peer dependency for the useFuse composable.

npm install fuse.js@^7
yarn add fuse.js

Install @vueuse/firebase

Source: https://vueuse.org/firebase/README

Install the package along with the required firebase dependency.

npm i @vueuse/firebase firebase

Basic useNow Usage

Source: https://vueuse.org/core/usenow

Import and use the useNow function to get a reactive Date instance. No additional setup is required.

import {
useNow
} from '@vueuse/core'

const
now
=
useNow()


useAxios Basic Usage

Source: https://vueuse.org/integrations/useAxios

Demonstrates the basic setup for useAxios to fetch data from a given URL.

## useAxios Basic Usage

### Description
This snippet shows the fundamental way to use the `useAxios` composable to fetch data from an API endpoint. It automatically triggers the request when the component is mounted if a URL is provided.

### Method
GET (default)

### Endpoint
`/api/posts`

### Parameters
#### Query Parameters
None

#### Request Body
None

### Request Example
```ts
import { useAxios } from '@vueuse/integrations/useAxios'

const { data, isFinished } = useAxios('/api/posts')

Response

Success Response (200)

  • data (Ref) - Response data
  • response (Ref) - Full axios response
  • isFinished (Ref) - Request has completed (success or error)

Response Example

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

--------------------------------

### Install jwt-decode dependency

Source: https://vueuse.org/integrations/useJwt

Install the required peer dependency for useJwt.

```bash
npm install jwt-decode@^4

useBluetooth - Battery Level Example

Source: https://vueuse.org/core/useBluetooth

An advanced example demonstrating how to read the battery level from a Bluetooth device and listen for changes using the useBluetooth composable.

## useBluetooth with Battery Service

### Description
This example shows how to use `useBluetooth` to connect to a device, access the 'battery_service', read the 'battery_level' characteristic, and set up a listener for value changes.

### Method
N/A (Composable function)

### Endpoint
N/A (Composable function)

### Parameters
#### Options Object
- **acceptAllDevices** (boolean) - Optional - If true, all devices will be accepted. Defaults to false.
- **optionalServices** (string[]) - Required for this example - `['battery_service']` to access battery information.

### Return Values
- **isSupported** (ComputedRef<boolean>) - Whether the Web Bluetooth API is supported.
- **isConnected** (Ref<boolean>) - Whether a device is currently connected.
- **device** (Ref<BluetoothDevice>) - The connected Bluetooth device.
- **server** (Ref<BluetoothRemoteGATTServer>) - The GATT server for the connected device.
- **requestDevice** (() => Promise<void>) - Function to request a Bluetooth device.

### Request Example
```javascript
import { useBluetooth, useEventListener, watchPausable } from '@vueuse/core'
import { ref } from 'vue'

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
  const batteryService = await server.getPrimaryService('battery_service')
  const batteryLevelCharacteristic = await batteryService.getCharacteristic('battery_level')

  useEventListener(batteryLevelCharacteristic, 'characteristicvaluechanged', (event) => {
    batteryPercent.value = event.target.value.getUint8(0)
  }, { passive: true })

  const batteryLevel = await batteryLevelCharacteristic.readValue()
  batteryPercent.value = await batteryLevel.getUint8(0)
}

const { stop } = watchPausable(isConnected, (newIsConnected) => {
  if (!newIsConnected || !server.value || isGettingBatteryLevels.value)
    return
  getBatteryLevels()
  stop()
})

Response

Success Response (Battery Level Read)

  • batteryPercent (number | undefined) - The current battery percentage.

Response Example

{
  "batteryPercent": 85
}

--------------------------------

### Create Disposable Directive with useMouse

Source: https://vueuse.org/shared/createdisposabledirective

Example of creating a custom directive using `createDisposableDirective`. Reactive effects like `useMouse` are automatically cleaned up on unmount. Ensure `@vueuse/core` and `@vueuse/shared` are installed.

```typescript
import {
  useMouse
} from '@vueuse/core'
import {
  createDisposableDirective
} from '@vueuse/shared'

export const VDirective = 
createDisposableDirective({
  mounted(el, binding) {
    const value = binding.value

    if (typeof value === 'function') {
      // [`useMouse`](/core/useMouse/) event listener will be removed automatically when directive is unmounted
      const { x, y } = useMouse()
      
      watch(x, val => value(val))
    }
  }
})

Wizard state example

Source: https://vueuse.org/core/useStepper

Example of the internal state object managed by useStepper.

{
  "steps": {
    "user-information": {
      "title": "User information"
    },
    "billing-address": {
      "title": "Billing address"
    },
    "terms": {
      "title": "Terms"
    },
    "payment": {
      "title": "Payment"
    }
  },
  "stepNames": [
    "user-information",
    "billing-address",
    "terms",
    "payment"
  ],
  "index": 0,
  "current": {
    "title": "User information"
  },
  "next": "billing-address",
  "isFirst": true,
  "isLast": false
}

Basic Usage of useMousePressed

Source: https://vueuse.org/core/useMousePressed

Import and use the useMousePressed function to get the reactive pressed state. No additional setup is required for basic mouse tracking.

import {
useMousePressed
} from '@vueuse/core'

const { 
pressed
 } = 
useMousePressed
()

Get Mouse Leave State

Source: https://vueuse.org/core/usepageleave

Import and use the usePageLeave function to get a reactive boolean indicating if the mouse has left the page. No additional setup is required.

import {
  usePageLeave
} from '@vueuse/core'

const isLeft = 
usePageLeave
()

Usage Example

Source: https://vueuse.org/shared/createRef

Demonstrates how to use the createRef function in both TypeScript and JavaScript.

## Usage

### TypeScript
```typescript
import { createRef } from '@vueuse/core'
import { isShallow, ref } from 'vue'

const initialData = 1

const shallowData = createRef(initialData)
const deepData = createRef(initialData, true)

isShallow(shallowData) // true
isShallow(deepData) // false

JavaScript

import { createRef } from '@vueuse/core'
import { isShallow } from 'vue'

const initialData = 1
const shallowData = createRef(initialData)
const deepData = createRef(initialData, true)

isShallow(shallowData) // true
isShallow(deepData) // false

--------------------------------

### Import and Use useOnline Hook

Source: https://vueuse.org/core/useOnline

Import the useOnline hook from '@vueuse/core' and use it to get a reactive online status. No additional setup is required.

```typescript
import {
useOnline
} from '@vueuse/core'

const
online
=
useOnline()


Install Fuse.js with NPM

Source: https://vueuse.org/integrations/useFuse

Install Fuse.js version 7 or higher as a peer dependency using NPM.

npm install fuse.js@^7

Install async-validator

Source: https://vueuse.org/integrations/useAsyncValidator

Install the async-validator package, which is a peer dependency for useAsyncValidator.

npm i async-validator@^4

useWindowSize - Basic Usage

Source: https://vueuse.org/core/useWindowSize

This snippet demonstrates the basic usage of the useWindowSize composable to get the reactive window width and height.

## useWindowSize - Basic Usage

### Description
This composable provides reactive window width and height.

### Method
Composition API function

### Endpoint
N/A (Client-side composable)

### Parameters
None for basic usage.

### Request Example
```vue
<script setup lang="ts">
import { useWindowSize } from '@vueuse/core'

const { width, height } = useWindowSize()
</script>

<template>
  <div>
    Width: {{ width }}
    Height: {{ height }}
  </div>
</template>

Response

  • width (ShallowRef) - Reactive reference to the window's width.
  • height (ShallowRef) - Reactive reference to the window's height.

Response Example

{
  "width": 1280,
  "height": 800
}

--------------------------------

### Initialize useSpeechSynthesis

Source: https://vueuse.org/core/useSpeechSynthesis

Basic setup to access speech synthesis controls and state.

```typescript
import { 
useSpeechSynthesis
 } from '@vueuse/core'

const {
  
isSupported
,
  
isPlaying
,
  
status
,
  
voiceInfo
,
  
utterance
,
  
error
,
  
stop
,
  
toggle
,
  
speak
,
} = 
useSpeechSynthesis
()

useMin - Basic Usage with Multiple Arguments

Source: https://vueuse.org/math/useMin

Demonstrates how to use useMin with multiple reactive number arguments.

## useMin with Multiple Arguments

### Description
Calculates the minimum value from a list of reactive numbers provided as arguments.

### Method
Composable function

### Endpoint
N/A (Composable Function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
import { ref } from 'vue'
import { useMin } from '@vueuse/math'

const a = ref(1)
const b = ref(3)
const c = ref(2)

const min = useMin(a, b, c)
// min will be a Ref<1>

Response

Success Response

  • min (Ref) - A computed ref containing the minimum value.

Response Example

{
  "min": 1
}

--------------------------------

### Get Device Orientation State

Source: https://vueuse.org/core/useDeviceOrientation

Import and destructure the reactive properties from useDeviceOrientation. This composable requires no additional setup.

```typescript
import {
  useDeviceOrientation
} from '@vueuse/core'

const {
  isAbsolute,
  alpha,
  beta,
  gamma,
} = 
useDeviceOrientation
()

useWebSocket Basic Usage

Source: https://vueuse.org/core/useWebSocket

Demonstrates the basic setup for useWebSocket, including establishing a connection and accessing core properties like status, data, and control functions.

## useWebSocket Basic Usage

### Description
Establishes a reactive WebSocket connection and provides access to connection status, received data, and methods to control the connection.

### Method
`useWebSocket(url: string, options?: UseWebSocketOptions)

### Endpoint
N/A (Client-side composable)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
import { useWebSocket } from '@vueuse/core'

const { status, data, send, open, close, ws } = useWebSocket('ws://websocketurl')

Response

Success Response (Connection Established)

  • data (Ref) - Latest received data
  • status (Ref<'OPEN' | 'CONNECTING' | 'CLOSED'>) - Connection status
  • ws (Ref) - WebSocket instance
  • send (Function) - Function to send data over the WebSocket connection
  • open (Function) - Function to open or reconnect the connection
  • close (Function) - Function to close the connection

Response Example

{
  "data": "Received message content",
  "status": "OPEN",
  "ws": "WebSocket object",
  "send": "function",
  "open": "function",
  "close": "function"
}

--------------------------------

### Install @vueuse/router

Source: https://vueuse.org/router/README

Install the @vueuse/router package along with vue-router v5. Ensure you have npm installed.

```bash
npm i @vueuse/router vue-router@5

Install axios dependency

Source: https://vueuse.org/integrations/useAxios

Install the required axios package before using the integration.

npm i axios@^1

Install drauu dependency

Source: https://vueuse.org/integrations/useDrauu

Install the required drauu package before using the integration.

npm i drauu@^0

Basic Media Controls Setup

Source: https://vueuse.org/core/useMediaControls

Sets up reactive controls for a video element, including playback, current time, duration, and volume. Initializes volume and current time on component mount.

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

const
video
=
useTemplateRef('video')
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>

Import and Use usePreferredDark

Source: https://vueuse.org/core/usePreferredDark

Import the usePreferredDark composable and use it to get a reactive boolean indicating the user's dark theme preference. No additional setup is required.

import {
usePreferredDark
} from '@vueuse/core'

const
isDark
=
usePreferredDark
()

Use useElementBounding in Script Setup

Source: https://vueuse.org/core/useElementBounding

Import and use useElementBounding with useTemplateRef to get reactive bounding box properties of an element. Ensure the element has a ref attribute matching the one passed to useTemplateRef.

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

const 
el
 = 
useTemplateRef
('el')
const { 
x
, 
y
, 
top
, 
right
, 
bottom
, 
left
, 
width
, 
height
 } = 
useElementBounding
(
el
)
</script>

<template>
  <div 
ref
="
el
" />
</template>

Use useTrunc for Reactive Truncation

Source: https://vueuse.org/math/useTrunc

Import and use the useTrunc function with refs to get reactive truncated numbers. Ensure you have '@vueuse/math' installed.

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

Initialize useRefHistory

Source: https://vueuse.org/core/userefhistory

Basic setup for tracking a ref's history.

import { 
useRefHistory
 } from '@vueuse/core'
import { 
shallowRef
 } from 'vue'

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

Initialize useFileSystemAccess

Source: https://vueuse.org/core/usefilesystemaccess

Demonstrates the import and destructuring of the composable's state and methods.

import { 
useFileSystemAccess
 } from '@vueuse/core'

const {
  
isSupported
,
  
data
,
  
file
,
  
fileName
,
  
fileMIME
,
  
fileSize
,
  
fileLastModified
,
  
create
,
  
open
,
  
save
,
  
saveAs
,
  
updateData

} = 
useFileSystemAccess
()

Use native ref in script setup

Source: https://vueuse.org/core/templateRef

When using <script setup>, native Vue ref is preferred as variables are automatically exposed to the template.

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

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

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

Install Fuse.js with Yarn

Source: https://vueuse.org/integrations/useFuse

Install Fuse.js version 7 or higher as a peer dependency using Yarn.

yarn add fuse.js

Reactive Math.min Usage

Source: https://vueuse.org/math/usemin

Examples demonstrating how to use useMin with arrays or multiple reactive arguments.

import { 
useMin
 } from '@vueuse/math'

const 
array
 = 
ref
([1, 2, 3, 4])
const 
min
 = 
useMin
(
array
) // Ref<1>
import { 
useMin
 } from '@vueuse/math'

const 
a
 = 
ref
(1)
const 
b
 = 
ref
(3)

const 
min
 = 
useMin
(
a
, 
b
, 2) // Ref<1>

createReusableTemplate Usage (Options API)

Source: https://vueuse.org/core/createreusabletemplate

Example showing how to integrate createReusableTemplate with Vue's Options API, requiring registration in the components option.

## createReusableTemplate Usage (Options API)

### Description
This example illustrates how to use `createReusableTemplate` within a Vue component using the Options API. The returned template components need to be explicitly registered.

### Method
`createReusableTemplate` function

### Endpoint
N/A (Composable function)

### Parameters
None directly for the function call.

### Request Example
```vue
<script>
import { createReusableTemplate } from '@vueuse/core'
import { defineComponent } from 'vue'

const [DefineTemplate, ReuseTemplate] = createReusableTemplate()

export default defineComponent({
  components: {
    DefineTemplate,
    ReuseTemplate,
  },
  setup() {
    // ...
  },
})
</script>

<template>
  <DefineTemplate v-slot="{ data, msg, anything ">
    <div>{{ data }} passed from usage</div>
  </DefineTemplate>

  <ReuseTemplate :data="data" msg="The first usage" />
</template>

Response

  • <DefineTemplate>: Registers the template and renders nothing.
  • <ReuseTemplate>: Renders the template provided by <DefineTemplate>.

Response Example

N/A (Component rendering example.)


--------------------------------

### useNow - Component Usage

Source: https://vueuse.org/core/useNow

Example of using the `UseNow` renderless component for `useNow`.

```APIDOC
## UseNow Component

### Description
Renderless component version of the `useNow` composable.

### Usage
```vue
<template>
  <UseNow v-slot="{ now, pause, resume }">
    Now: {{ now }}
    <button @click="pause()">
      Pause
    </button>
    <button @click="resume()">
      Resume
    </button>
  </UseNow>
</template>

--------------------------------

### useUserMedia Basic Usage

Source: https://vueuse.org/core/useusermedia

Demonstrates the basic integration of useUserMedia to start and display a media stream from the user's camera.

```APIDOC
## POST /api/users

### Description
This endpoint allows for the creation of a new user.

### Method
POST

### Endpoint
/api/users

### Parameters
#### Request Body
- **username** (string) - Required - The desired username for the new user.
- **email** (string) - Required - The email address of the new user.
- **password** (string) - Required - The password for the new user.

### Request Example
{
  "username": "johndoe",
  "email": "john.doe@example.com",
  "password": "securepassword123"
}

### Response
#### Success Response (201)
- **id** (string) - The unique identifier for the newly created user.
- **username** (string) - The username of the created user.
- **email** (string) - The email address of the created user.

#### Response Example
{
  "id": "user-12345",
  "username": "johndoe",
  "email": "john.doe@example.com"
}

useDark - Basic Usage

Source: https://vueuse.org/core/useDark

Demonstrates the basic setup of the useDark composable to enable reactive dark mode.

## useDark - Basic Usage

### Description
This example shows the fundamental way to integrate `useDark` into your Vue application.

### Method
`useDark()`

### Endpoint
N/A (Composable Function)

### Parameters
None for basic usage.

### Request Body
None.

### Request Example
```typescript
import { useDark, useToggle } from '@vueuse/core'

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

Response

  • isDark (WritableComputedRef) - A reactive boolean indicating the current dark mode state.

Response Example

// The 'isDark' ref will be true or false based on the current mode.
// Example: true

--------------------------------

### Import and Use VueUse Functions

Source: https://vueuse.org/guide

Import specific functions from @vueuse/core and use them within a setup script.

```vue
<script setup>
import { 
useLocalStorage
, 
useMouse
, 
usePreferredDark
 } from '@vueuse/core'

// 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',
  },
)
</script>

useMin - Basic Usage with Array

Source: https://vueuse.org/math/useMin

Demonstrates how to use useMin with a reactive array of numbers.

## useMin with Array

### Description
Calculates the minimum value from a reactive array of numbers.

### Method
Composable function

### Endpoint
N/A (Composable Function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
import { ref } from 'vue'
import { useMin } from '@vueuse/math'

const array = ref([1, 2, 3, 4])
const min = useMin(array)
// min will be a Ref<1>

Response

Success Response

  • min (Ref) - A computed ref containing the minimum value.

Response Example

{
  "min": 1
}

--------------------------------

### Use useAbs for Reactive Absolute Value

Source: https://vueuse.org/math/useAbs

Import and use the `useAbs` function to get the absolute value of a reactive number. Ensure you have `@vueuse/math` installed and `ref` from Vue imported.

```typescript
import {
useAbs
} from '@vueuse/math'

const 
value
 = 
ref
(-23)
const 
absoluteValue
 = 
useAbs
(
value
) // Ref<23>

Start Promise Execution

Source: https://vueuse.org/core/createtemplatepromise

Invoking the start method to trigger the promise lifecycle.

const 
result
 = await 
TemplatePromise
.
start
()
'use strict'
const result = await TemplatePromise.start()

Tailwind CSS Configuration Example

Source: https://vueuse.org/core/useDark

Demonstrates the expected HTML structure for Tailwind CSS dark mode.

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

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

Provide SSR Width - Root Component Example

Source: https://vueuse.org/core/useSSRWidth

Example of how to provide the SSR width within the root component of your Vue application.

## Provide SSR Width - Root Component

### Description
This example shows how to use `provideSSRWidth` directly in your root Vue component's setup to establish a global SSR viewport width.

### Method
`provideSSRWidth`

### Endpoint
N/A (Composable function)

### Parameters
- **width** (number) - The SSR viewport width (e.g., 500).

### Request Example
```vue
<script setup lang="ts">
import { provideSSRWidth } from '@vueuse/core'

// Provide a global SSR width of 500px in the root component
provideSSRWidth(500)
</script>

<template>
  <!-- Your app content -->
</template>

--------------------------------

### Initialize useWebWorker

Source: https://vueuse.org/core/useWebWorker

Basic setup for registering a Web Worker using a file path.

```typescript
import { 
useWebWorker
 } from '@vueuse/core'

const { 
data
, 
post
, 
terminate
, 
worker
 } = 
useWebWorker
('/path/to/worker.js')

useClamp - Basic Usage

Source: https://vueuse.org/math/useclamp

Demonstrates the basic usage of useClamp with shallow refs for min and max values.

## useClamp 

### Description
Reactively clamp a value between two other values.

### Method
Composition API function

### Endpoint
N/A (Client-side utility)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
import { useClamp } from '@vueuse/math'
import { shallowRef } from 'vue'

const min = shallowRef(0)
const max = shallowRef(10)
const value = useClamp(0, min, max)

Response

Success Response (200)

Returns a computed ref that clamps the input value.

Response Example

{
  "clampedValue": 5 
}

--------------------------------

### useStepper with Steps as Array

Source: https://vueuse.org/core/usestepper

This example demonstrates how to use the `useStepper` composable with an array of step names. It shows how to import the function and access various state properties and methods like `current`, `next`, `previous`, `goTo`, and `goToNext`.

```APIDOC
## useStepper with Steps as Array

### Description
This example demonstrates how to use the `useStepper` composable with an array of step names. It shows how to import the function and access various state properties and methods like `current`, `next`, `previous`, `goTo`, and `goToNext`.

### Method
`useStepper`

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
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'

Response

Success Response (200)

This composable does not have a direct success response in the traditional API sense, as it's a client-side utility. The return value is an object containing reactive state and methods for managing the stepper.

  • steps (Ref<Array<string | number>>) - List of steps.
  • stepNames (Ref<Array<string | number>>) - List of step names.
  • index (Ref) - Index of the current step.
  • current (ComputedRef<string | number>) - Current step.
  • next (ComputedRef<string | number | undefined>) - Next step, or undefined if the current step is the last one.
  • previous (ComputedRef<string | number | undefined>) - Previous step, or undefined if the current step is the first one.
  • isFirst (ComputedRef) - Whether the current step is the first one.
  • isLast (ComputedRef) - Whether the current step is the last one.
  • at (Function) - Get the step at the specified index.
  • get (Function) - Get a step by the specified name.
  • goTo (Function) - Go to the specified step.
  • goToNext (Function) - Go to the next step. Does nothing if the current step is the last one.
  • goToPrevious (Function) - Go to the previous step. Does nothing if the current step is the previous one.
  • goBackTo (Function) - Go back to the given step, only if the current step is after.
  • isNext (Function) - Checks whether the given step is the next step.
  • isPrevious (Function) - Checks whether the given step is the previous step.
  • isCurrent (Function) - Checks whether the given step is the current step.
  • isBefore (Function) - Checks if the current step is before the given step.
  • isAfter (Function) - Checks if the current step is after the given step.

Response Example

{
  "steps": [
    "billing-address",
    "terms",
    "payment"
  ],
  "stepNames": [
    "billing-address",
    "terms",
    "payment"
  ],
  "index": 0,
  "current": "billing-address",
  "next": "terms",
  "previous": undefined,
  "isFirst": true,
  "isLast": false
}

--------------------------------

### Install Fuse.js

Source: https://vueuse.org/integrations/useFuse

Fuse.js is a peer dependency for useFuse. Install it using npm or yarn.

```APIDOC
## Install Fuse.js

### NPM
```bash
npm install fuse.js@^7

Yarn

yarn add fuse.js

--------------------------------

### Track Window Focus in Vue Component

Source: https://vueuse.org/core/useWindowFocus

Import and use `useWindowFocus` in your Vue component's script setup to get a reactive boolean indicating window focus. Display the focus state in the template.

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

const 
focused
 = 
useWindowFocus
()
</script>

<template>
  <
div
>{{ 
focused
 }}</
div
>
</template>

useChangeCase with Options

Source: https://vueuse.org/integrations/useChangeCase

Demonstrates how to use useChangeCase with custom options for further customization.

## useChangeCase with Options

### Description
Example of using `useChangeCase` with a `ref` and custom options.

### Method
`useChangeCase`

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
import { useChangeCase } from '@vueuse/integrations/useChangeCase'
import { shallowRef } from 'vue'

const input = shallowRef('helloWorld')
const changeCase = useChangeCase(input, 'camelCase', {
  delimiter: '-',
})

changeCase.value // hello-World

input.value = 'vue use'
changeCase.value // vue-Use

Response

Success Response (200)

WritableComputedRef<string> or ComputedRef<string> depending on input.

Response Example

{
  "example": "hello-World"
}

--------------------------------

### useWebNotification Basic Usage

Source: https://vueuse.org/core/usewebnotification

Demonstrates the basic setup and usage of the useWebNotification composable to show a notification if supported and permissions are granted.

```APIDOC
## useWebNotification

### Description
Provides a reactive interface for the Web Notification API to display desktop notifications.

### Method
Composable Function

### Endpoint
N/A (Client-side composable)

### Parameters
#### Request Body (Options for `useWebNotification`)
- **title** (string) - Optional - The title of the notification.
- **body** (string) - Optional - The main content of the notification.
- **dir** ("auto" | "ltr" | "rtl") - Optional - Text direction of the notification.
- **lang** (string) - Optional - Language code for the notification.
- **tag** (string) - Optional - An identifier for the notification.
- **icon** (string) - Optional - URL of an icon for the notification.
- **renotify** (boolean) - Optional - If true, new notifications will replace old ones with the same tag.
- **requireInteraction** (boolean) - Optional - If true, the notification stays until the user interacts with it.
- **silent** (boolean) - Optional - If true, the notification will be silent.
- **vibrate** (number[]) - Optional - Vibration pattern for devices with vibration hardware.
- **requestPermissions** (boolean) - Optional - Request permissions on mount. Defaults to true.

### Request Example
```typescript
import { useWebNotification } from '@vueuse/core'

const { isSupported, notification, permissionGranted, show, close } = useWebNotification({
  title: 'Hello, VueUse world!',
  dir: 'auto',
  lang: 'en',
  renotify: true,
  tag: 'test',
})

if (isSupported.value && permissionGranted.value) {
  show()
}

Response

Success Response (Composable Return)

  • isSupported (ShallowRef) - Indicates if the browser supports Web Notifications.
  • notification (ShallowRef<Notification | null>) - The Notification object.
  • permissionGranted (ShallowRef) - Indicates if notification permissions are granted.
  • show (function) - Function to display the notification. Accepts optional overrides.
  • close (function) - Function to close the notification.
  • onClick (EventHookOn) - Hook for the 'click' event.
  • onShow (EventHookOn) - Hook for the 'show' event.
  • onError (EventHookOn) - Hook for the 'error' event.
  • onClose (EventHookOn) - Hook for the 'close' event.
  • ensurePermissions (function) - Function to explicitly request permissions.

--------------------------------

### Convert Ref to RxJS Observer in TypeScript

Source: https://vueuse.org/rxjs/toobserver

Use toObserver to subscribe RxJS streams to a Vue ref. Ensure @vueuse/rxjs is installed. The example demonstrates updating a 'count' ref using an RxJS interval, stopping on button click.

```typescript
import { from, fromEvent, toObserver, useSubscription } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map, mapTo, startWith, takeUntil, withLatestFrom } from 'rxjs/operators'
import { shallowRef, useTemplateRef } from 'vue'

const count = shallowRef(0)
const button = useTemplateRef('buttonRef')

useSubscription(
  interval(1000)
    .pipe(
      mapTo(1),
      takeUntil(fromEvent(button, 'click')),
      withLatestFrom(from(count).pipe(startWith(0))),
      map(([curr, total]) => curr + total),
    )
    .subscribe(toObserver(count)), // same as ).subscribe(val => (count.value = val))
)

useBase64 - Basic Usage

Source: https://vueuse.org/core/usebase64

Demonstrates the basic usage of useBase64 with a text input. It shows how to import the function and use it with a shallowRef.

## useBase64 - Basic Usage

### Description
This snippet shows the fundamental usage of the `useBase64` function with a plain text input.

### Method
`useBase64`

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
import { useBase64 } from '@vueuse/core'
import { shallowRef } from 'vue'

const text = shallowRef('')

const { base64, promise, execute } = useBase64(text)

Response

Success Response (200)

  • base64 (ShallowRef) - The resulting base64 string.
  • promise (ShallowRef<Promise>) - The promise of the current transformation.
  • execute (Function) - Manually trigger the transformation.

Response Example

{
  "base64": "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==",
  "promise": "Promise<string>",
  "execute": "function"
}

--------------------------------

### Access ref.value with get()

Source: https://vueuse.org/shared/get

Use this utility to get the value of a ref. Ensure you have imported `get` from '@vueuse/core'.

```typescript
import {
get
} from '@vueuse/core'

const a = ref(42)

console.log(get(a)) // 42

useNow - Basic Usage

Source: https://vueuse.org/core/useNow

This snippet demonstrates the basic usage of the useNow composable to get a reactive Date instance.

## useNow

### Description
Reactive current Date instance.

### Method
`useNow`

### Parameters
#### Options
- **options** (UseNowOptions<false>) - Optional - Configuration options for the composable.
  - **controls** (boolean) - Optional - Expose more controls. Defaults to `false`.
  - **immediate** (boolean) - Optional - Start the clock immediately. Defaults to `true`. Deprecated, use `scheduler` instead.
  - **interval** ("requestAnimationFrame" | number) - Optional - Update interval in milliseconds, or use requestAnimationFrame. Defaults to `requestAnimationFrame`. Deprecated, use `scheduler` instead.

### Returns
- **now** (ShallowRef<Date>) - A shallow reactive reference to the current Date.

### Request Example
```ts
import { useNow } from '@vueuse/core'

const now = useNow()

--------------------------------

### Install idb-keyval dependency

Source: https://vueuse.org/integrations/useIDBKeyval

Requires idb-keyval as a peer dependency.

```bash
npm install idb-keyval@^6

Options API usage

Source: https://vueuse.org/core/usevmodel

Implementation within the setup function of an Options API component.

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')
  },
}

Usage of injectLocal and provideLocal

Source: https://vueuse.org/shared/injectLocal

Demonstrates how to provide a value locally and immediately inject it within the same component setup.

<script setup>
import { 
injectLocal
, 
provideLocal
 } from '@vueuse/core'


provideLocal
('MyInjectionKey', 1)
const 
injectedValue
 = 
injectLocal
('MyInjectionKey') // injectedValue === 1
</script>

useFavicon Basic Usage

Source: https://vueuse.org/core/usefavicon

This example demonstrates the basic usage of useFavicon to change the favicon to a static image.

## useFavicon

### Description

Allows you to reactively control the browser favicon.

### Method

`useFavicon(newIcon?: MaybeRef<string | null | undefined>, options?: UseFaviconOptions): Ref<string | null | undefined>`

### Parameters

#### Request Body

- **newIcon** (Ref<string | null | undefined> | string | null | undefined) - Optional - The new favicon URL or path.
- **options** (UseFaviconOptions) - Optional - Configuration options.
  - **baseUrl** (string) - Optional - Base URL for the favicon.
  - **rel** (string) - Optional - The 'rel' attribute for the favicon link tag.

### Request Example

```typescript
import { useFavicon } from '@vueuse/core'

const icon = useFavicon()

icon.value = 'dark.png' // change current icon

Response

Returns a Ref that controls the favicon.

Success Response (200)

  • icon (Ref<string | null | undefined>) - A ref that controls the favicon.

Response Example

{
  "icon": "dark.png"
}

--------------------------------

### Usage Example (TypeScript)

Source: https://vueuse.org/core/usepreferredcolorscheme

Demonstrates how to import and use the `usePreferredColorScheme` composable in a TypeScript Vue component.

```APIDOC
## Usage Example (TypeScript)

### Description
Import and use the `usePreferredColorScheme` composable to get the user's preferred color scheme.

### Method
Composable Function

### Endpoint
N/A

### Parameters
N/A

### Request Body
N/A

### Response
#### Success Response
- **preferredColor** (ComputedRef<ColorSchemeType>) - A computed reference holding the current color scheme.

### Request Example
```typescript
import { usePreferredColorScheme } from '@vueuse/core'

const preferredColor = usePreferredColorScheme()

Response Example

{
  "preferredColor": "dark"
}

--------------------------------

### useDevicesList - Basic Usage

Source: https://vueuse.org/core/usedeviceslist

Demonstrates the basic reactive enumeration of devices using `useDevicesList`.

```APIDOC
## GET /api/devices

### Description
Retrieves a reactive list of available audio and video input/output devices.

### Method
GET

### Endpoint
/api/devices

### Parameters
#### Query Parameters
- **requestPermissions** (boolean) - Optional - If true, requests permissions immediately.
- **constraints** (object) - Optional - MediaStreamConstraints to specify requested media types (e.g., { audio: true, video: true }).

### Response
#### Success Response (200)
- **devices** (ShallowRef<MediaDeviceInfo[]>) - A shallow reference to an array of all available media devices.
- **videoInputs** (ComputedRef<MediaDeviceInfo[]>) - A computed reference to an array of video input devices (cameras).
- **audioInputs** (ComputedRef<MediaDeviceInfo[]>) - A computed reference to an array of audio input devices (microphones).
- **audioOutputs** (ComputedRef<MediaDeviceInfo[]>) - A computed reference to an array of audio output devices (speakers).
- **permissionGranted** (ShallowRef<boolean>) - A shallow reference indicating if permissions have been granted.
- **ensurePermissions** (function) - A function that returns a Promise resolving to a boolean indicating if permissions were successfully ensured.

### Request Example
```ts
import { useDevicesList } from '@vueuse/core'

const { devices, videoInputs: cameras, audioInputs: microphones, audioOutputs: speakers } = useDevicesList()

Response Example

{
  "devices": [
    {
      "deviceId": "device-id-1",
      "kind": "videoinput",
      "label": "Camera 1",
      "groupId": "group-id-1"
    },
    {
      "deviceId": "device-id-2",
      "kind": "audioinput",
      "label": "Microphone 1",
      "groupId": "group-id-2"
    }
  ],
  "videoInputs": [
    {
      "deviceId": "device-id-1",
      "kind": "videoinput",
      "label": "Camera 1",
      "groupId": "group-id-1"
    }
  ],
  "audioInputs": [
    {
      "deviceId": "device-id-2",
      "kind": "audioinput",
      "label": "Microphone 1",
      "groupId": "group-id-2"
    }
  ],
  "audioOutputs": [],
  "permissionGranted": true,
  "ensurePermissions": "[Function: ensurePermissions]"
}

--------------------------------

### useAxios with Config Options

Source: https://vueuse.org/integrations/useaxios

Configure the request method and other axios options when using useAxios. This example demonstrates making a POST request.

```typescript
import {
useAxios
} from '@vueuse/integrations/useAxios'
import 
axios
 from 'axios'

const 
instance
 =
axios
.
create
({
 aseURL
: '/api',
})

const { 
data
,
isFinished
 } = 
useAxios
('/posts', { 
method
: 'POST' }, 
instance
)

useMax - Reactive Maximum

Source: https://vueuse.org/math/usemax

Demonstrates how to use useMax with an array of numbers to get a reactive maximum value.

## useMax (Array Input)

### Description
Calculates the maximum value from a reactive array of numbers.

### Method
Composable function

### Endpoint
N/A (Vue.js Composable)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```ts
import { ref } from 'vue'
import { useMax } from '@vueuse/math'

const array = ref([1, 2, 3, 4])
const max = useMax(array)
// max will be a Ref<4>

Response

Success Response

  • max (Ref) - A Vue ref containing the maximum number from the input array.

Response Example

{
  "max": 4
}

--------------------------------

### Transition with Delay and Callbacks

Source: https://vueuse.org/core/usetransition

Control the transition start time with a delay and execute functions when the transition starts or finishes.

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

VueUse get() Type Declarations

Source: https://vueuse.org/shared/get

These are the type declarations for the get() utility, showing how it handles refs and keys.

/**
 * 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]

Usage of tryOnBeforeUnmount

Source: https://vueuse.org/shared/tryOnBeforeUnmount

Import and execute the function within a component setup context.

import { 
tryOnBeforeUnmount
 } from '@vueuse/core'


tryOnBeforeUnmount
(() => {

})

useAxios with Axios Instance

Source: https://vueuse.org/integrations/useAxios

Shows how to use a pre-configured Axios instance with the useAxios composable.

## useAxios with Axios Instance

### Description
This snippet illustrates how to integrate `useAxios` with an existing Axios instance, allowing you to leverage custom configurations like `baseURL`.

### Method
GET (default)

### Endpoint
`/posts` (relative to the instance's baseURL)

### Parameters
#### Query Parameters
None

#### Request Body
None

### Request Example
```ts
import { useAxios } from '@vueuse/integrations/useAxios'
import axios from 'axios'

const instance = axios.create({
  baseURL: '/api',
})

const { data, isFinished } = useAxios('/posts', instance)

Response

Success Response (200)

  • data (Ref) - Response data
  • isFinished (Ref) - Request has completed (success or error)

Response Example

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

--------------------------------

### Basic usage of useUserMedia

Source: https://vueuse.org/core/useUserMedia

Demonstrates how to initialize a media stream and bind it to a video element using a template reference.

```vue
<script setup lang="ts">
import { 
useUserMedia
 } from '@vueuse/core'
import { 
useTemplateRef
, 
watchEffect
 } from 'vue'

const { 
stream
, 
start
 } = 
useUserMedia
()

start
()

const 
videoRef
 = 
useTemplateRef
('video')

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

})
</script>

<template>
  <
video
 
ref
="
video
" />
</template>

Initialize useDevicesList

Source: https://vueuse.org/core/useDevicesList

Import and destructure the useDevicesList composable to get reactive lists of devices. Aliases can be used for clarity.

import {
  useDevicesList
} from '@vueuse/core'

const {
  devices,
  videoInputs: cameras,
  audioInputs: microphones,
  audioOutputs: speakers,
} = 
useDevicesList
()

onStartTyping Function

Source: https://vueuse.org/core/onStartTyping

Registers a callback that fires when the user starts typing on non-editable elements.

## onStartTyping

### Description
Fires a callback when users start typing on non-editable elements. The callback only triggers if no editable element is focused, the key is alphanumeric, and no modifier keys are held.

### Parameters
#### Arguments
- **callback** (Function) - Required - A function to execute when typing is detected. Receives the KeyboardEvent as an argument.
- **options** (ConfigurableDocument) - Optional - Configuration object for the document target.

### Request Example
```typescript
import { onStartTyping } from '@vueuse/core'

onStartTyping((event) => {
  console.log('User started typing:', event.key)
})

Response

  • void - This function does not return a value.

--------------------------------

### Display JWT Header

Source: https://vueuse.org/integrations/useJwt

Example of a JWT header structure.

```json
{
  "alg": "HS256",
  "typ": "JWT"
}

useTimeout with Callback

Source: https://vueuse.org/shared/useTimeout

This example shows how to provide a callback function that executes once the timeout completes.

## useTimeout with Callback

### Description

This example demonstrates how to provide a `callback` function to `useTimeout`. The provided function will be executed automatically once the timeout duration has elapsed.

### Method

`useTimeout`

### Parameters

#### Path Parameters

None

#### Query Parameters

None

#### Request Body

None

### Request Example

```ts
import { useTimeout } from '@vueuse/core'

useTimeout(1000, {
  callback: () => {
    console.log('Timeout completed!')
  },
})

Response

Success Response (200)

None (The primary effect is the execution of the callback function).

Response Example

// No direct JSON response, but 'Timeout completed!' will be logged to the console.

useTransition with Delay and Callbacks

Source: https://vueuse.org/core/useTransition

Configures a delay before the transition starts and defines onStarted and onFinished callbacks.

## GET /api/products

### Description
Retrieves a list of products.

### Method
GET

### Endpoint
/api/products

### Parameters
#### Query Parameters
- **category** (string) - Optional - Filter products by category.
- **sort** (string) - Optional - Field to sort products by (e.g., 'price', 'name').
- **order** (string) - Optional - Sort order ('asc' or 'desc').

### Response
#### Success Response (200)
- **products** (array) - An array of product objects.
  - **id** (integer) - Product ID.
  - **name** (string) - Product name.
  - **price** (number) - Product price.
  - **category** (string) - Product category.

#### Response Example
```json
{
  "products": [
    {
      "id": 101,
      "name": "Laptop",
      "price": 1200.00,
      "category": "Electronics"
    },
    {
      "id": 102,
      "name": "Keyboard",
      "price": 75.00,
      "category": "Electronics"
    }
  ]
}

--------------------------------

### useEventSource with Named Events

Source: https://vueuse.org/core/useEventSource

This example shows how to listen for specific named events emitted by the server by providing an array of event names.

```APIDOC
## useEventSource with Named Events

### Description
Allows listening for specific named events from the server by providing an array of event names.

### Method
`useEventSource(url: string | Ref<string>, eventNames: string[])`

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
const { event, data } = useEventSource('https://event-source-url', ['notice', 'update'])

Response

Success Response (200)

  • event (Ref<string | null>) - The name of the received event.
  • data (Ref<string | null>) - The data associated with the received event.

Response Example

{
  "event": "update",
  "data": "User profile updated"
}

--------------------------------

### Install VueUse AI Agent Skills

Source: https://vueuse.org/guide/work-with-ai

Use this command to add the VueUse AI Agent Skills to your project. This is the first step to enable AI assistance for VueUse.

```bash
npx skills add vueuse/skills

Initialize useSpeechRecognition

Source: https://vueuse.org/core/useSpeechRecognition

Basic setup for accessing speech recognition state and control methods.

import { 
useSpeechRecognition
 } from '@vueuse/core'

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

Configure custom clone functions

Source: https://vueuse.org/core/useManualRefHistory

Provides examples for using structuredClone, lodash-es, or klona for deep cloning.

import { 
useManualRefHistory
 } from '@vueuse/core'

const 
refHistory
 = 
useManualRefHistory
(target, { 
clone
: 
structuredClone
 })
import { 
useManualRefHistory
 } from '@vueuse/core'
import { 
cloneDeep
 } from 'lodash-es'

const 
refHistory
 = 
useManualRefHistory
(target, { 
clone
: 
cloneDeep
 })
import { 
useManualRefHistory
 } from '@vueuse/core'
import { 
klona
 } from 'klona'

const 
refHistory
 = 
useManualRefHistory
(target, { 
clone
: 
klona
 })

useBase64 - Basic Usage

Source: https://vueuse.org/core/useBase64

Demonstrates the basic usage of the useBase64 composable with a text input.

## useBase64 - Basic Usage

### Description
This example shows how to use the `useBase64` composable with a reactive string reference.

### Method
`useBase64`

### Parameters
#### Target
- **target** (Ref<string | undefined>) - A reactive reference to the string to be encoded.

#### Options
- **dataUrl** (boolean) - Optional. If true, the output will be in Data URL format. Defaults to true.

### Return Values
- **base64** (Ref<string>) - A reactive reference to the base64 encoded string.
- **promise** (Ref<Promise<string>>) - A reactive reference to the promise of the current transformation.
- **execute** - A function to manually trigger the transformation.

### Request Example
```typescript
import { useBase64 } from '@vueuse/core'
import { shallowRef } from 'vue'

const text = shallowRef('')

const { base64, promise, execute } = useBase64(text)

Response Example

{
  "base64": "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==",
  "promise": "Promise<string>",
  "execute": "() => Promise<string>"
}

--------------------------------

### Basic usage

Source: https://vueuse.org/integrations/useAxios

Perform a simple GET request using the useAxios hook.

```typescript
import { 
useAxios
 } from '@vueuse/integrations/useAxios'

const { 
data
, 
isFinished
 } = 
useAxios
('/api/posts')

Lazy Initialization

Source: https://vueuse.org/core/computedasync

Configure computedAsync to start resolving only on first access.

## computedAsync - Lazy Loading

### Description
Defer the execution of the async function until the computed property is first accessed.

### Parameters
#### Options
- `lazy` (boolean): Set to `true` to enable lazy loading.
- `evaluating` (Ref<boolean>): A ref to track the evaluation status (optional).

### Request Example
```typescript
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'

const evaluating = shallowRef(false)
const userInfo = computedAsync(
  async () => { /* your logic */ },
  null,
  { lazy: true, evaluating } // Options object
)

--------------------------------

### useNow - With Controls

Source: https://vueuse.org/core/useNow

This snippet shows how to use `useNow` with the `controls` option enabled to get pause and resume functions.

```APIDOC
## useNow with Controls

### Description
Reactive current Date instance with pause and resume controls.

### Method
`useNow`

### Parameters
#### Options
- **options** (UseNowOptions<true>) - Required - Configuration options for the composable.
  - **controls** (boolean) - Required - Expose more controls. Must be `true` for this overload.
  - **immediate** (boolean) - Optional - Start the clock immediately. Defaults to `true`. Deprecated, use `scheduler` instead.
  - **interval** ("requestAnimationFrame" | number) - Optional - Update interval in milliseconds, or use requestAnimationFrame. Defaults to `requestAnimationFrame`. Deprecated, use `scheduler` instead.

### Returns
- **now** (ShallowRef<Date>) - A shallow reactive reference to the current Date.
- **pause** (function) - Function to pause the clock.
- **resume** (function) - Function to resume the clock.

### Request Example
```ts
import { useNow } from '@vueuse/core'

const { now, pause, resume } = useNow({ controls: true })

Response Example

{
  "now": "2023-10-27T10:00:00.000Z",
  "pause": "function",
  "resume": "function"
}

--------------------------------

### Basic Infinite Scroll Setup

Source: https://vueuse.org/core/useinfinitescroll

Set up infinite scrolling for an element. Ensure `canLoadMore` correctly indicates when no more content is available to prevent unnecessary triggers.

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

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

const { reset } = useInfiniteScroll(
  el,
  () => {
    // load more
    data.value.push(...moreData)
  },
  {
    distance: 10,
    canLoadMore: () => {
      // inidicate when there is no more content to load so onLoadMore stops triggering
      // if (noMoreContent) return false
      return true // for demo purposes
    },
  }
)

function resetList() {
  data.value = []
  reset()
}
</script>

<template>
  <div ref="el">
    <div v-for="item in data">
      {{ item }}
    </div>
  </div>
  <button @click="resetList()">
    Reset
  </button>
</template>

useBluetooth - Default Usage

Source: https://vueuse.org/core/useBluetooth

Demonstrates the basic setup and usage of the useBluetooth composable to request and connect to a Bluetooth device.

## useBluetooth

### Description
Provides a reactive interface to the Web Bluetooth API, allowing discovery and communication with Bluetooth Low Energy peripherals.

### Method
N/A (Composable function)

### Endpoint
N/A (Composable function)

### Parameters
#### Options Object
- **acceptAllDevices** (boolean) - Optional - If true, all devices will be accepted. Defaults to false.
- **optionalServices** (string[]) - Optional - An array of service UUIDs to request.

### Return Values
- **isSupported** (ComputedRef<boolean>) - Whether the Web Bluetooth API is supported by the browser.
- **isConnected** (Ref<boolean>) - Whether a Bluetooth device is currently connected.
- **device** (Ref<BluetoothDevice>) - The connected Bluetooth device object.
- **server** (Ref<BluetoothRemoteGATTServer>) - The GATT server object for the connected device.
- **error** (Ref<unknown>) - Any error encountered during the Bluetooth interaction.
- **requestDevice** (() => Promise<void>) - A function that initiates the device discovery and connection process.

### Request Example
```javascript
import { useBluetooth } from '@vueuse/core'

const { isSupported, isConnected, device, requestDevice, server, error } = useBluetooth({
  acceptAllDevices: true,
})

Response

Success Response (Connection Established)

  • device (BluetoothDevice) - The connected device object.
  • server (BluetoothRemoteGATTServer) - The GATT server for the device.

Response Example

{
  "isConnected": true,
  "device": { ...BluetoothDevice object... },
  "server": { ...BluetoothRemoteGATTServer object... }
}

--------------------------------

### useMath - Basic Usage

Source: https://vueuse.org/math/usemath

Demonstrates how to use the useMath composable with different Math functions like 'pow' and 'sqrt'.

```APIDOC
## useMath

### Description
Reactive `Math` methods.

### Method
`useMath(key: UseMathKeys, ...args: ArgumentsType<Reactified<Math[K], true>>): UseMathReturn<K>

### Parameters

#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
import { ref } from 'vue'
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

Response

Success Response (200)

Returns a Ref containing the result of the Math operation.

Response Example

{
  "example": "8" 
}

Error Handling

N/A


--------------------------------

### Basic usage of useNow

Source: https://vueuse.org/core/useNow

Import and initialize the useNow composable to get a reactive Date instance.

```ts
import { 
useNow
 } from '@vueuse/core'

const 
now
 = 
useNow
()

Equivalent of templateRef with Vue's ref in <script setup>

Source: https://vueuse.org/core/templateref

When using <script setup> in Vue, the native ref function provides the same functionality as templateRef for binding to template elements. All variables declared with ref are automatically exposed to the template.

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

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

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

Handling Initial Load with useStorageAsync

Source: https://vueuse.org/core/usestorageasync

Explains how to manage scenarios where the initial value from async storage might be empty before it's fully loaded. It shows how to wait for the storage to be ready.

## GET /api/users/{id}

### Description
Retrieves a specific user by their ID.

### Method
GET

### Endpoint
/api/users/{id}

### Parameters
#### Path Parameters
- **id** (integer) - Required - The unique identifier of the user to retrieve.

#### Query Parameters
- **fields** (string) - Optional - A comma-separated list of fields to include in the response.

### Response
#### Success Response (200)
- **id** (integer) - The unique identifier for the user.
- **name** (string) - The name of the user.
- **email** (string) - The email address of the user.
- **createdAt** (string) - The timestamp when the user was created.

#### Response Example
```json
{
  "id": 1,
  "name": "John Doe",
  "email": "john.doe@example.com",
  "createdAt": "2023-10-27T10:00:00Z"
}

--------------------------------

### Basic useTransition Setup

Source: https://vueuse.org/core/usetransition

Define a source value and use useTransition to animate its changes over a specified duration with a preset easing function.

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

const source = shallowRef(0)

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

Usage Example

Source: https://vueuse.org/shared/refAutoReset

Demonstrates how to use the refAutoReset function in a Vue component to manage a message that resets after a delay.

## Usage

```typescript
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'
}

Info: You can reassign the entire object to trigger updates after making deep mutations to the inner value. Learn more about shallow refs →


--------------------------------

### Initialize useCounter with Options

Source: https://vueuse.org/shared/useCounter

Initialize the useCounter composable with a starting value and options for minimum and maximum bounds.

```typescript
import {
useCounter
} from '@vueuse/core'

const { 
count
,
inc
,
dec
,
set
,
reset
} = 
useCounter
(1, { 
min
: 0, 
max
: 16 })

Install Nuxt Module

Source: https://vueuse.org/guide

Add the VueUse module to a Nuxt project using the CLI or package manager.

npx nuxt@latest module add vueuse
npm i -D @vueuse/nuxt @vueuse/core

useWindowSize - Options

Source: https://vueuse.org/core/useWindowSize

This snippet details the available options for configuring the useWindowSize composable.

## useWindowSize - Options

### Description
Configure the behavior of the `useWindowSize` composable with various options.

### Method
Composition API function

### Endpoint
N/A (Client-side composable)

### Parameters
#### Query Parameters
None

#### Request Body
None

#### Options Object (`UseWindowSizeOptions`)
- **initialWidth** (number) - Optional - The initial width value.
- **initialHeight** (number) - Optional - The initial height value.
- **listenOrientation** (boolean) - Optional - Listen to window `orientationchange` event. Defaults to `true`.
- **includeScrollbar** (boolean) - Optional - Whether the scrollbar should be included in the width and height. Only effective when `type` is `'inner'`. Defaults to `true`.
- **type** (string) - Optional - Use `window.innerWidth`, `window.outerWidth`, or `window.visualViewport`. Possible values: `'inner'`, `'outer'`, `'visual'`. Defaults to `'inner'`.

### Request Example
```vue
<script setup lang="ts">
import { useWindowSize } from '@vueuse/core'

const { width, height } = useWindowSize({
  includeScrollbar: false,
  type: 'outer'
})
</script>

<template>
  <div>
    Width: {{ width }}
    Height: {{ height }}
  </div>
</template>

Response

  • width (ShallowRef) - Reactive reference to the window's width.
  • height (ShallowRef) - Reactive reference to the window's height.

Response Example

(Depends on the options and window state)

{
  "width": 1280,
  "height": 800
}

--------------------------------

### Start Polling with useTimeoutPoll

Source: https://vueuse.org/core/useTimeoutPoll

Use this snippet to initiate a polling mechanism. It takes a fetch function and an interval, ensuring the fetch function completes before the next interval starts. The hook returns controls to manage the polling state.

```typescript
import {
useTimeoutPoll
} from '@vueuse/core'

const
count
=
ref
(0)

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

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


Display JWT Payload

Source: https://vueuse.org/integrations/useJwt

Example of a JWT payload structure.

{
  "sub": "1234567890",
  "iat": 1516239022
}

transition Manual Execution

Source: https://vueuse.org/core/useTransition

Demonstrates manually triggering a transition using the transition function and how to cancel it.

## POST /api/orders

### Description
Creates a new order.

### Method
POST

### Endpoint
/api/orders

### Parameters
#### Request Body
- **userId** (integer) - Required - The ID of the user placing the order.
- **items** (array) - Required - An array of items in the order.
  - **productId** (integer) - Required - The ID of the product.
  - **quantity** (integer) - Required - The quantity of the product.
- **shippingAddress** (object) - Required - The shipping address for the order.
  - **street** (string) - Required.
  - **city** (string) - Required.
  - **zipCode** (string) - Required.
  - **country** (string) - Required.

### Request Example
```json
{
  "userId": 1,
  "items": [
    {
      "productId": 101,
      "quantity": 1
    }
  ],
  "shippingAddress": {
    "street": "123 Main St",
    "city": "Anytown",
    "zipCode": "12345",
    "country": "USA"
  }
}

Response

Success Response (201)

  • orderId (integer) - The unique identifier for the newly created order.
  • status (string) - The status of the order (e.g., 'pending', 'processing').

Response Example

{
  "orderId": 5001,
  "status": "pending"
}

--------------------------------

### Get and Set CSS Variables

Source: https://vueuse.org/core/useCssVar

Demonstrates how to use useCssVar to get and set CSS variables. It shows usage with a direct element reference, a template ref with a dynamic variable name, and with an initial value.

```typescript
import {
  useCssVar
} from '@vueuse/core'
import {
  useTemplateRef
} from 'vue'

const el = 
useTemplateRef('el')
const color1 = 
useCssVar('--color', el)

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

const someEl = 
useTemplateRef('someEl')
const color2 = 
useCssVar('--color', someEl, { 
initialValue: '#eee' })

Use usePrecision Hook

Source: https://vueuse.org/math/useprecision

Demonstrates how to use the usePrecision hook with different rounding methods. Ensure you have '@vueuse/math' installed and imported.

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

Basic Usage of useRouteQuery

Source: https://vueuse.org/router/useRouteQuery

Demonstrates basic initialization, default values, and type transformation for route query parameters.

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' } })

useTimestamp - Basic Usage

Source: https://vueuse.org/core/useTimestamp

Import and use the useTimestamp composable to get a reactive timestamp.

## useTimestamp 

### Description
Reactive current timestamp.

### Method
Composition API function

### Endpoint
N/A (Composable)

### Parameters
#### Query Parameters
- **options** (object) - Optional - Configuration options for useTimestamp.
  - **offset** (number) - Optional - Offset value to add to the timestamp. Defaults to 0.
  - **controls** (boolean) - Optional - If true, exposes pause and resume functions. Defaults to false.
  - **immediate** (boolean) - Optional - Update the timestamp immediately. Defaults to true. (Deprecated, use `scheduler` instead)
  - **interval** ("requestAnimationFrame" | number) - Optional - Update interval. Defaults to `requestAnimationFrame`. (Deprecated, use `scheduler` instead)
  - **callback** ((timestamp: number) => void) - Optional - Callback function executed on each timestamp update.
  - **scheduler** ("requestAnimationFrame" | number | (() => void)) - Optional - Custom scheduler for updates.

### Request Example
```json
{
  "offset": 1000,
  "controls": true
}

Response

  • timestamp (ShallowRef) - The reactive timestamp.
  • pause (function) - Function to pause timestamp updates (only if controls is true).
  • resume (function) - Function to resume timestamp updates (only if controls is true).

Response Example

{
  "timestamp": 1776449480915,
  "pause": "function",
  "resume": "function"
}

--------------------------------

### useCloned - Manual Synchronization

Source: https://vueuse.org/core/usecloned

Illustrates how to use `useCloned` with the `manual: true` option, requiring explicit calls to `sync()` to update the cloned ref.

```APIDOC
## useCloned - Manual Synchronization

### Description
This example shows how to use `useCloned` in manual mode. When `manual` is set to `true`, the `cloned` ref is not automatically updated when the `source` ref changes. You must call the `sync()` function to update the `cloned` ref.

### Method
`useCloned(source: MaybeRefOrGetter<T>, options?: UseClonedOptions<T>): UseClonedReturn<T>

### Parameters
#### Source
- **source** (Ref<T> | T | () => T) - Required - The ref or value to clone.

#### Options
- **clone** (function) - Optional - A custom function to perform the cloning. Defaults to `cloneFnJSON`.
- **manual** (boolean) - Required - Set to `true` to enable manual synchronization.

### Request Example
```typescript
import { ref } from 'vue'
import { useCloned } from '@vueuse/core'

const original = ref({ key: 'value' })
const { cloned, sync } = useCloned(original, { manual: true })

original.value.key = 'manual'
console.log(cloned.value.key) // Output: 'value'

sync()
console.log(cloned.value.key) // Output: 'manual'

Response

Success Response

  • cloned (Ref) - A ref containing the cloned data, updated only when sync() is called.
  • isModified (Ref) - A ref indicating if the cloned data has been modified compared to the source.
  • sync (function) - A function to manually synchronize the cloned data with the source.

Response Example

{
  "cloned": {"key": "manual"},
  "isModified": true,
  "sync": "[Function: sync]"
}

--------------------------------

### useUserMedia with Device Selection

Source: https://vueuse.org/core/useusermedia

Shows how to use useUserMedia in conjunction with useDevicesList to select specific cameras and microphones.

```APIDOC
## GET /api/users/{id}

### Description
Retrieves the details of a specific user by their unique identifier.

### Method
GET

### Endpoint
/api/users/{id}

### Parameters
#### Path Parameters
- **id** (string) - Required - The unique identifier of the user to retrieve.

### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the user.
- **username** (string) - The username of the user.
- **email** (string) - The email address of the user.

#### Response Example
{
  "id": "user-12345",
  "username": "johndoe",
  "email": "john.doe@example.com"
}

useInfiniteScroll - Basic Usage

Source: https://vueuse.org/core/useInfiniteScroll

Demonstrates the basic implementation of useInfiniteScroll for loading more data as the user scrolls.

## POST /api/users

### Description
This endpoint allows you to create a new user in the system.

### Method
POST

### Endpoint
/api/users

### Parameters
#### Request Body
- **name** (string) - Required - The name of the user.
- **email** (string) - Required - The email address of the user.

### Request Example
```json
{
  "name": "John Doe",
  "email": "john.doe@example.com"
}

Response

Success Response (201)

  • id (string) - The unique identifier of the newly created user.
  • name (string) - The name of the user.
  • email (string) - The email address of the user.

Response Example

{
  "id": "user-123",
  "name": "John Doe",
  "email": "john.doe@example.com"
}

--------------------------------

### useElementBounding - Basic Usage

Source: https://vueuse.org/core/useelementbounding

Demonstrates how to use the useElementBounding composable to get the reactive bounding box of an HTML element.

```APIDOC
## useElementBounding

### Description
Reactive bounding box of an HTML element.

### Method
Composable Function

### Endpoint
N/A (Composable Function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```vue
<script setup lang="ts">
import { useElementBounding } from '@vueuse/core'
import { useTemplateRef } from 'vue'

const el = useTemplateRef('el')
const { x, y, top, right, bottom, left, width, height } = useElementBounding(el)
</script>

<template>
  <div ref="el" />
</template>

Response

Success Response (Composable Return)

  • x (ShallowRef) - The x-coordinate of the element's bounding box.
  • y (ShallowRef) - The y-coordinate of the element's bounding box.
  • top (ShallowRef) - The top coordinate of the element's bounding box.
  • right (ShallowRef) - The right coordinate of the element's bounding box.
  • bottom (ShallowRef) - The bottom coordinate of the element's bounding box.
  • left (ShallowRef) - The left coordinate of the element's bounding box.
  • width (ShallowRef) - The width of the element's bounding box.
  • height (ShallowRef) - The height of the element's bounding box.
  • update (() => void) - A function to manually trigger an update of the bounding box.

Response Example

{
  "x": 10,
  "y": 20,
  "top": 20,
  "right": 150,
  "bottom": 120,
  "left": 10,
  "width": 140,
  "height": 100
}

--------------------------------

### Usage of tryOnUnmounted

Source: https://vueuse.org/shared/tryOnUnmounted

Import and execute the function within a component setup.

```typescript
import { 
tryOnUnmounted
 } from '@vueuse/core'


tryOnUnmounted
(() => {

})

useAxios with Config Options

Source: https://vueuse.org/integrations/useAxios

Demonstrates how to pass custom Axios request configurations to useAxios.

## useAxios with Config Options

### Description
This snippet shows how to provide specific request configurations, such as the HTTP method, when using `useAxios`.

### Method
POST

### Endpoint
`/posts` (relative to the instance's baseURL)

### Parameters
#### Query Parameters
None

#### Request Body
None (implicitly handled by Axios config if provided)

### Request Example
```ts
import { useAxios } from '@vueuse/integrations/useAxios'
import axios from 'axios'

const instance = axios.create({
  baseURL: '/api',
})

const { data, isFinished } = useAxios('/posts', { method: 'POST' }, instance)

Response

Success Response (200)

  • data (Ref) - Response data
  • isFinished (Ref) - Request has completed (success or error)

Response Example

{
  "message": "Post created successfully"
}

--------------------------------

### useStorage Options in JavaScript

Source: https://vueuse.org/core/useStorage

Shows the configuration options for useStorage in JavaScript, mirroring the TypeScript example for deep watching, cross-tab synchronization, and error handling.

```javascript
'use strict'
useStorage('key', defaults, storage, {
  // Watch for deep changes in objects/arrays (default: true)
  deep: true,
  // Sync across tabs via storage events (default: true)
  listenToStorageChanges: true,
  // Write default value to storage if not present (default: true)
  writeDefaults: true,
  // Use shallowRef instead of ref (default: false)
  shallow: false,
  // Initialize only after component is mounted (default: false)
  initOnMounted: false,
  // Custom error handler (default: console.error)
  onError: (e) => console.error(e),
  // Watch flush timing (default: 'pre')
  flush: 'pre',
})

Battery Status Demo Output

Source: https://vueuse.org/core/usebattery

Example output showing the reactive state values returned by the Battery API.

isSupported: true
charging: true
chargingTime: 0
dischargingTime: .inf
level: 1


Basic Usage of watchIgnorable

Source: https://vueuse.org/shared/watchIgnorable

Demonstrates how to use watchIgnorable to log changes to a source, with examples of ignoring updates and observing subsequent logged changes.

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

const source = shallowRef('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!

useDateFormat with Locales

Source: https://vueuse.org/shared/useDateFormat

Illustrates how to use useDateFormat with specific locales to format dates, using 'en-US' as an example for day names.

## useDateFormat with Locales

### Description
This example demonstrates using `useDateFormat` with the `locales` option to specify the language for date formatting. Here, 'en-US' is used to format the day of the week.

### Method
`useDateFormat(date, formatString, options)`

### Endpoint
N/A (Composable Function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```vue
<script setup lang="ts">
import {
useDateFormat,
useNow
} from '@vueuse/core'

const
formatted
=
useDateFormat(
useNow(), 'YYYY-MM-DD (ddd)', { locales: 'en-US' })
</script>

<template>
  <div>{{ formatted }}</div>
</template>

Response

Success Response (200)

N/A (Composable Function returns a ComputedRef<string>)

Response Example

{
  "example": "2023-10-27 (Fri)"
}

--------------------------------

### useRouteQuery Basic Usage

Source: https://vueuse.org/router/useroutequery

Demonstrates the basic usage of useRouteQuery to get and set URL query parameters. It shows how to initialize with a name, with a default value, and with value transformation.

```APIDOC
## useRouteQuery Basic Usage

### Description
This composable provides a shorthand for a reactive `route.query`. It updates the URL query parameters when the ref changes.

### Method
`useRouteQuery(name: string, defaultValue?: MaybeRefOrGetter<T>, options?: ReactiveRouteOptionsWithTransform<T, K>): Ref<K>
`

### Parameters
#### Path Parameters
None

#### Query Parameters
- **name** (string) - Required - The name of the query parameter.
- **defaultValue** (MaybeRefOrGetter<T>) - Optional - The default value for the query parameter.
- **options** (ReactiveRouteOptionsWithTransform<T, K>) - Optional - Configuration options for the composable.
  - **mode** ('push' | 'replace') - The navigation mode to use ('push' or 'replace'). Defaults to 'replace'.
  - **transform** (object) - An object with `get` and `set` functions for transforming the value.
    - **get** (function) - Function to transform the value when reading from the URL.
    - **set** (function) - Function to transform the value when writing to the URL.

### Request Example
ts
```typescript
import { useRouteQuery } from '@vueuse/router'

const search = useRouteQuery('search')
const searchWithDefault = useRouteQuery('search', 'foo')
const page = useRouteQuery('page', '1', { transform: Number })

console.log(search.value) // route.query.search
search.value = 'foobar' // router.replace({ query: { search: 'foobar' } })

Response

Success Response (200)

Returns a Ref object that is synchronized with the specified route query parameter.

Response Example

{
  "value": "current_query_param_value"
}

--------------------------------

### useFavicon with a Source Ref

Source: https://vueuse.org/core/usefavicon

This example shows how to pass a `ref` to `useFavicon`. Changes to the source ref will automatically update the favicon.

```APIDOC
## useFavicon with Source Ref

### Description

Pass a `ref` to `useFavicon`. Changes from the source ref will be reflected to your favicon automatically. When a source ref is passed, the return ref will be identical to the source ref.

### Method

`useFavicon(newIcon: ReadonlyRefOrGetter<string | null | undefined>, options?: UseFaviconOptions): ComputedRef<string | null | undefined>`

### Parameters

#### Request Body

- **newIcon** (ReadonlyRefOrGetter<string | null | undefined>) - Required - A ref or getter that provides the favicon URL or path.
- **options** (UseFaviconOptions) - Optional - Configuration options.
  - **baseUrl** (string) - Optional - Base URL for the favicon.
  - **rel** (string) - Optional - The 'rel' attribute for the favicon link tag.

### Request Example

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

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

useFavicon(favicon)

Response

Returns a ComputedRef that is identical to the source ref.

Success Response (200)

  • icon (ComputedRef<string | null | undefined>) - A computed ref that controls the favicon, identical to the source ref.

Response Example

{
  "icon": "light.png"
}

--------------------------------

### useWindowFocus - Basic Usage

Source: https://vueuse.org/core/usewindowfocus

Demonstrates how to use the `useWindowFocus` composable to track the window's focus state in a Vue component.

```APIDOC
## useWindowFocus

### Description
Reactively track window focus with `window.onfocus` and `window.onblur` events.

### Method
Composable Function

### Endpoint
N/A (Composable Function)

### Parameters
#### Query Parameters
- **options** (ConfigurableWindow) - Optional - Configuration options for the window.

### Request Example
```vue
<script setup lang="ts">
import { useWindowFocus } from '@vueuse/core'

const focused = useWindowFocus()
</script>

<template>
  <div>{{ focused }}</div>
</template>

Response

Success Response (200)

  • focused (ShallowRef) - A reactive reference indicating whether the window is currently focused.

--------------------------------

### useTimeout Basic Usage

Source: https://vueuse.org/shared/useTimeout

A simple example of using useTimeout to set a timeout of 1000ms. The `ready` ref will become true after the timeout.

```APIDOC
## useTimeout Basic Usage

### Description

This example demonstrates the basic usage of the `useTimeout` composable. After the specified interval, a reactive boolean ref (`ready`) will be set to `true`.

### Method

`useTimeout`

### Parameters

#### Path Parameters

None

#### Query Parameters

None

#### Request Body

None

### Request Example

```ts
import { useTimeout } from '@vueuse/core'

const ready = useTimeout(1000)

Response

Success Response (200)

  • ready (ComputedRef) - A computed ref that becomes true after the timeout duration.

Response Example

{
  "ready": true // after 1 second
}

--------------------------------

### Writable computedInject

Source: https://vueuse.org/core/computedInject

Demonstrates how to create a writable computed property using computedInject with `get` and `set` functions.

```APIDOC
### Writable Computed

You can also create a writable computed property by passing an object with `get` and `set` functions.

```typescript
import { computedInject } from '@vueuse/core'

const computedArray = computedInject(ArrayKey, {
  get(source) {
    return source.value.map(item => item.value)
  },
  set(value) {
    // handle setting the value
    console.log('Setting value:', value)
  },
})

--------------------------------

### Initialize useRTDB

Source: https://vueuse.org/firebase/usertdb

Basic setup for binding a Firebase Realtime Database reference to a reactive variable.

```typescript
import { 
useRTDB
 } from '@vueuse/firebase/useRTDB'
import { 
initializeApp
 } from 'firebase/app'
import { 
getDatabase
 } from 'firebase/database'

const 
app
 = 
initializeApp
({ /* config */ })
const 
db
 = 
getDatabase
(
app
)

// in setup()
const 
todos
 = 
useRTDB
(
db
.ref('todos'))

usePreferredColorScheme - Basic Usage

Source: https://vueuse.org/core/usePreferredColorScheme

Demonstrates how to use the usePreferredColorScheme composable in a Vue TypeScript setup.

## usePreferredColorScheme

### Description
Reactive prefers-color-scheme media query.

### Method
`usePreferredColorScheme()`

### Parameters
None

### Request Example
```typescript
import {
  usePreferredColorScheme
} from '@vueuse/core'

const preferredColor = usePreferredColorScheme()

Response

Returns a ComputedRef<ColorSchemeType> which holds the current color scheme.

Success Response (200)

  • preferredColor (ComputedRef) - The current color scheme ('dark', 'light', or 'no-preference').

Response Example

{
  "preferredColor": "light"
}

--------------------------------

### Import and Initialize useBase64

Source: https://vueuse.org/core/usebase64

Import the useBase64 composable and initialize it with a reactive reference for text. This sets up the reactive base64 transformation.

```typescript
import {
  useBase64
} from '@vueuse/core'
import {
  shallowRef
} from 'vue'

const text = shallowRef('')

const { base64, promise, execute } = useBase64(text)

get Utility Function

Source: https://vueuse.org/shared/get

The get utility function is a shorthand for accessing ref.value. It can also be used to access properties of an object referenced by a ref.

## get

### Description
Shorthand for accessing `ref.value` or properties of a referenced object.

### Method
N/A (Utility Function)

### Endpoint
N/A (Utility Function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
import { get, ref } from '@vueuse/core'

const a = ref(42)
console.log(get(a)) // 42

const obj = ref({ count: 0 })
console.log(get(obj, 'count')) // 0

Response

Success Response (200)

  • T (any) - The value of the ref or the specified property.

Response Example

{
  "example": "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]

--------------------------------

### usePointer - Basic Usage

Source: https://vueuse.org/core/usepointer

Demonstrates how to import and use the `usePointer` function in a Vue component to get reactive pointer coordinates and other states.

```APIDOC
## usePointer - Basic Usage

### Description
This snippet shows the basic import and usage of the `usePointer` composable function to access reactive pointer properties like `x`, `y`, `pressure`, and `pointerType`.

### Method
Composable Function

### Endpoint
N/A (Client-side composable)

### Parameters
#### Query Parameters
- **options** (UsePointerOptions) - Optional - Configuration options for `usePointer`.

### Request Example
```typescript
import { usePointer } from '@vueuse/core'

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

Response

Success Response (Composable Return)

  • x (Ref) - The current X coordinate of the pointer.
  • y (Ref) - The current Y coordinate of the pointer.
  • pressure (Ref) - The pressure of the pointer (e.g., for stylus).
  • pointerType (Ref<PointerType | null>) - The type of pointer ('mouse', 'touch', 'pen').
  • pointerId (Ref) - The ID of the pointer.
  • tiltX (Ref) - The tilt of the pointer along the X-axis.
  • tiltY (Ref) - The tilt of the pointer along the Y-axis.
  • width (Ref) - The width of the pointer.
  • height (Ref) - The height of the pointer.
  • twist (Ref) - The twist of the pointer.
  • isInside (ShallowRef) - Whether the pointer is currently inside the target element.

Response Example

{
  "x": 150,
  "y": 200,
  "pressure": 0.5,
  "pointerType": "mouse",
  "pointerId": 0,
  "tiltX": 0,
  "tiltY": 0,
  "width": 0,
  "height": 0,
  "twist": 0,
  "isInside": true
}

--------------------------------

### useCloned - Manual Syncing

Source: https://vueuse.org/core/useCloned

Shows how to use the `manual: true` option with useCloned. This prevents automatic updates to the clone and requires calling the `sync` function to update it.

```APIDOC
## useCloned - Manual Syncing

### Description
Demonstrates using `useCloned` with the `manual: true` option. The clone is not updated automatically; you must call `sync()` to update it.

### Method
`useCloned`

### Parameters
#### Source Ref
- **source** (Ref<T> | MaybeRefOrGetter<T>) - Required - The ref to clone.

#### Options
- **options** (UseClonedOptions) - Optional - Configuration options for cloning.
  - **manual** (boolean) - Required - Set to `true` to enable manual syncing.

### Request Example
```typescript
import { ref } from 'vue'
import { useCloned } from '@vueuse/core'

const original = ref({ key: 'value' })
const { cloned, sync } = useCloned(original, { manual: true })

original.value.key = 'manual'
console.log(cloned.value.key) // 'value'

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

Response

Success Response

  • cloned (Ref) - A reactive ref containing the cloned data.
  • sync (function) - A function to manually sync the cloned data with the source ref.

Response Example

{
  "cloned": {"key": "value"},
  "sync": () => {}
}

--------------------------------

### Basic usePermission Usage

Source: https://vueuse.org/core/usePermission

Import and use the usePermission composable to get the reactive state for microphone access.

```typescript
import {
usePermission
} from '@vueuse/core'

const microphoneAccess
 = 
usePermission
('microphone')

Reactive mouse position output

Source: https://vueuse.org/core/usemouseinelement

Example output showing the reactive state properties of the mouse position relative to an element.

x: 0
y: 0
sourceType: null
elementX: -368
elementY: -480
elementPositionX: 368
elementPositionY: 480
elementHeight: 160
elementWidth: 160
isOutside: true

x: 0
y: 0
sourceType: null
elementX: -384
elementY: -838
elementPositionX: 384
elementPositionY: 838
elementHeight: 20
elementWidth: 127.859375
isOutside: true


Using the Custom Fetch Hook in a Vue Component

Source: https://vueuse.org/shared/createeventhook

Demonstrates how to consume the useMyFetch composable within a Vue 3 setup script. It shows how to subscribe to onResult and onError events.

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

useDevicesList()

Source: https://vueuse.org/core/useDevicesList

A reactive utility to enumerate available media devices and manage permissions.

## useDevicesList()

### Description
Reactive enumerateDevices listing available input/output devices.

### Parameters
#### Options
- **onUpdated** (function) - Optional - Callback triggered when devices are updated.
- **requestPermissions** (boolean) - Optional - Whether to request permissions immediately if not granted. Default: false.
- **constraints** (MediaStreamConstraints) - Optional - Media types to request permissions for. Default: { audio: true, video: true }.

### Response
- **devices** (ShallowRef<MediaDeviceInfo[]>) - All available devices.
- **videoInputs** (ComputedRef<MediaDeviceInfo[]>) - List of video input devices.
- **audioInputs** (ComputedRef<MediaDeviceInfo[]>) - List of audio input devices.
- **audioOutputs** (ComputedRef<MediaDeviceInfo[]>) - List of audio output devices.
- **permissionGranted** (ShallowRef<boolean>) - Current permission status.
- **ensurePermissions** (function) - Async function to request device permissions.

injectLocal Usage

Source: https://vueuse.org/shared/injectLocal

Demonstrates how to use provideLocal and injectLocal within a Vue component's script setup.

## POST /api/users

### Description
This endpoint allows for the creation of a new user in the system.

### Method
POST

### Endpoint
/api/users

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
- **username** (string) - Required - The desired username for the new user.
- **email** (string) - Required - The email address of the new user.
- **password** (string) - Required - The password for the new user.

### Request Example
```json
{
  "username": "johndoe",
  "email": "john.doe@example.com",
  "password": "securepassword123"
}

Response

Success Response (201)

  • id (string) - The unique identifier for the newly created user.
  • username (string) - The username of the created user.
  • email (string) - The email address of the created user.

Response Example

{
  "id": "user-12345",
  "username": "johndoe",
  "email": "john.doe@example.com"
}

--------------------------------

### Component Usage Example (Vue SFC)

Source: https://vueuse.org/core/usepreferredcolorscheme

Shows how to use the renderless component version of `usePreferredColorScheme` within a Vue Single File Component (SFC).

```APIDOC
## Component Usage Example (Vue SFC)

### Description
Utilize the renderless component `UsePreferredColorScheme` for accessing the color scheme within a Vue template.

### Method
Renderless Component

### Endpoint
N/A

### Parameters
N/A

### Request Body
N/A

### Response
#### Success Response
- **colorScheme** (string) - The detected color scheme ('dark', 'light', or 'no-preference').

### Request Example
```vue
<template>
  <UsePreferredColorScheme v-slot="{ colorScheme }">
    Preferred Color Scheme: {{ colorScheme }}
  </UsePreferredColorScheme>
</template>

<script setup>
import { UsePreferredColorScheme } from '@vueuse/components';
</script>

Response Example

Preferred Color Scheme: light

--------------------------------

### Get Current Component Element

Source: https://vueuse.org/core/useCurrentElement

Import and use `useCurrentElement` to get the DOM element of the current component. The returned value is a `ComputedRef<Element>` and will be undefined until the component is mounted.

```typescript
import {
useCurrentElement
} from '@vueuse/core'

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

useCounter - Usage with Options

Source: https://vueuse.org/shared/usecounter

Illustrates how to use the useCounter composable with custom initial values and options like minimum and maximum bounds.

## useCounter - Usage with Options

### Description
This example demonstrates initializing the `useCounter` composable with a specific starting value and defining constraints using the `min` and `max` options.

### Method
`useCounter(initialValue, options)`

### Parameters
- **initialValue** (number, optional) - The starting value for the counter. Defaults to 0.
- **options** (object, optional) - Configuration options for the counter.
  - **min** (number, optional) - The minimum allowed value for the counter.
  - **max** (number, optional) - The maximum allowed value for the counter.

### Request Example
```typescript
import { useCounter } from '@vueuse/core'

const { count, inc, dec, set, reset } = useCounter(1, { min: 0, max: 16 })

Response

  • count (Ref) - The current value of the counter, respecting min/max bounds.
  • inc (function) - Function to increment the counter.
  • dec (function) - Function to decrement the counter.
  • set (function) - Function to set the counter to a specific value.
  • reset (function) - Function to reset the counter to its initial value.

Response Example

{
  "count": 1,
  "inc": "function",
  "dec": "function",
  "set": "function",
  "reset": "function"
}

--------------------------------

### Import and Initialize useWakeLock

Source: https://vueuse.org/core/useWakeLock

Import the useWakeLock composable and destructure its reactive properties and methods. This setup is necessary to interact with the Screen Wake Lock API.

```typescript
import {
useWakeLock
} from '@vueuse/core'

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

Get Parent Element by Template Ref

Source: https://vueuse.org/core/useParentElement

Pass a template ref to useParentElement to get the parent element of a specific element within your template. The element must be mounted to have a parent.

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

const tooltip = 
useTemplateRef
('tooltip')

const tooltipWrapper = 
useParentElement
(
tooltip
)

onMounted(() => {
  console.log(tooltipWrapper.value)
})
</script>

<template>
  <div>
    <p ref="tooltip" />
  </div>
</template>

useConfirmDialog - Basic Usage

Source: https://vueuse.org/core/useConfirmDialog

Demonstrates the basic usage of useConfirmDialog with template-based control.

## useConfirmDialog - Basic Usage

### Description
This example shows how to use the `useConfirmDialog` composable to manage a modal dialog directly from the template.

### Method
`useConfirmDialog()`

### Parameters
- `revealed` (ShallowRef<boolean>) - Optional: A ref to control the revealed state of the dialog.

### Functions Returned
- `isRevealed` (ComputedRef<boolean>): Indicates if the dialog is currently revealed.
- `reveal` (Function): Triggers the dialog to be revealed and returns a promise.
- `confirm` (Function): Confirms the dialog action and closes it.
- `cancel` (Function): Cancels the dialog action and closes it.
- `onReveal` (EventHookOn): Hook triggered when the dialog is revealed.
- `onConfirm` (EventHookOn): Hook triggered when the dialog is confirmed.
- `onCancel` (EventHookOn): Hook triggered when the dialog is canceled.

### Request Example
```vue
<script setup lang="ts">
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>

--------------------------------

### Get Battery Status

Source: https://vueuse.org/core/useBattery

Import and use the `useBattery` composable to get reactive battery status. Ensure to check `isSupported` before using the values, as the Battery API has limited browser support.

```typescript
import {
  useBattery
} from '@vueuse/core'

const { 
  isSupported,
  charging,
  chargingTime,
  dischargingTime,
  level
} = 
useBattery
()

Delaying Animation Start

Source: https://vueuse.org/core/useAnimate

Demonstrates manual control of animation playback by setting immediate to false.

import { 
useAnimate
 } from '@vueuse/core'

const { 
play
 } = 
useAnimate
(el, keyframes, {
  
duration
: 1000,
  
immediate
: false,
})

// Start the animation manually

play
()

Get and Set Zoom Factor

Source: https://vueuse.org/electron/useZoomFactor

Import and use the useZoomFactor composable to get the current zoom factor and optionally set a new one. Ensure nodeIntegration is enabled if not explicitly providing a webFrame.

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

Customizing Cache Key with getKey

Source: https://vueuse.org/core/useMemoize

Demonstrates how to customize the cache key generation using the getKey option. This example ignores the headers argument when determining the cache key, using only userId.

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
,
  },
)
'use strict'
const getUser = useMemoize(
  async (userId, headers) =>
    axios.get(`users/${userId}`, { headers }).then(({ data }) => data),
  {
    // Use only userId to get/set cache and ignore headers
    getKey: (userId, headers) => userId,
  },
)

Get Reactive Browser Location

Source: https://vueuse.org/core/usebrowserlocation

Import and use the useBrowserLocation composable to get a reactive reference to the browser's location object. Note: If using Vue Router, prefer its useRoute hook.

import {
useBrowserLocation
} from '@vueuse/core'

const location = 
useBrowserLocation
()

useStyleTag API

Source: https://vueuse.org/core/usestyletag

Documentation for the useStyleTag composable, including its parameters, return values, and usage examples.

## useStyleTag

### Description
Inject reactive `<style>` element in head.

### Method
`useStyleTag(css: MaybeRef<string>, options?: UseStyleTagOptions): UseStyleTagReturn`

### Parameters
#### Request Body
- **css** (MaybeRef<string>) - The CSS string to inject.
- **options** (UseStyleTagOptions) - Optional configuration for the style tag.
  - **media** (string) - Media query for styles to apply.
  - **immediate** (boolean) - Load the style immediately. Defaults to `true`.
  - **manual** (boolean) - Manually control the timing of loading and unloading. Defaults to `false`.
  - **id** (string) - DOM id of the style tag. Defaults to auto-incremented.
  - **nonce** (string) - Nonce value for CSP (Content Security Policy).

### Return Values
- **id** (string) - The ID of the injected style tag.
- **css** (ShallowRef<string>) - A reactive reference to the CSS string.
- **load** - Function to load the style tag.
- **unload** - Function to unload the style tag.
- **isLoaded** (Readonly<ShallowRef<boolean>>) - A reactive boolean indicating if the style tag is loaded.

### Basic Usage
```typescript
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; }'

Custom ID

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

Media Query

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

--------------------------------

### Basic Gamepad Usage

Source: https://vueuse.org/core/useGamepad

Demonstrates how to access gamepad state and filter for standard-mapped controllers.

```vue
<script setup lang="ts">
import { 
useGamepad
 } from '@vueuse/core'
import { 
computed
 } from 'vue'

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

<template>
  <span>
    {{ gamepad.id }}
  </span>
</template>

Get and Set Route Hash

Source: https://vueuse.org/router/useroutehash

Import and use the useRouteHash composable to get the current route's hash value or set a new one. Setting the value uses router.replace to update the hash.

import {
useRouteHash
} from '@vueuse/router'

const
search
=
useRouteHash
()


console
.
log
(
search
.
value
)
// route.hash

search
.
value
=
'foobar'
// router.replace({ hash: 'foobar' })


Usage of useFloor

Source: https://vueuse.org/math/useFloor

Demonstrates importing and using useFloor with a reactive ref.

import { 
useFloor
 } from '@vueuse/math'

const 
value
 = 
ref
(45.95)
const 
result
 = 
useFloor
(
value
) // 45

Wait for some async data to be ready

Source: https://vueuse.org/shared/until

This example demonstrates how to use until to wait for asynchronous data fetched by useAsyncState to be ready before accessing its state.

## Wait for some async data to be ready

### Description
Waits for asynchronous data to be ready before proceeding.

### Method
`until(isReady).toBe(true)`

### Endpoint
N/A (Composition API function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
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!
})()

Response

Success Response (200)

N/A (This is a client-side composition function)

Response Example

N/A


--------------------------------

### useElementVisibility - Basic Usage

Source: https://vueuse.org/core/useelementvisibility

Tracks the visibility of an element within the viewport. This example shows basic usage with a template ref.

```APIDOC
## useElementVisibility

### Description
Tracks the visibility of an element within the viewport.

### Method
Composition API function

### Endpoint
N/A (Composable function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```vue
<script setup lang="ts">
import { useElementVisibility } from '@vueuse/core'
import { useTemplateRef } from 'vue'

const target = useTemplateRef('target')
const targetIsVisible = useElementVisibility(target)
</script>

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

Response

Success Response (N/A - Returns a Ref)

  • targetIsVisible (ShallowRef) - A ref that is true when the element is visible, false otherwise.

Response Example

{
  "isVisible": true
}

--------------------------------

### Basic Event Bus Usage (JavaScript)

Source: https://vueuse.org/core/useEventBus

Demonstrates how to create, listen to, emit, and unregister events using the useEventBus utility in plain JavaScript. Listeners registered within a component's setup are automatically cleaned up on unmount.

```javascript
import { useEventBus } from '@vueuse/core'
const bus = useEventBus('news')
function listener(event) {
  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()

Observe performance metrics

Source: https://vueuse.org/core/usePerformanceObserver

Demonstrates how to initialize the observer to track specific performance entry types.

import { 
usePerformanceObserver
 } from '@vueuse/core'

const 
entrys
 = 
ref
<PerformanceEntry[]>([])

usePerformanceObserver
({
  
entryTypes
: ['paint'],
}, (
list
) => {
  
entrys
.
value
 = 
list
.
getEntries
()
})
import { usePerformanceObserver } from '@vueuse/core'
const entrys = ref([])
usePerformanceObserver(
  {
    entryTypes: ['paint'],
  },
  (list) => {
    entrys.value = list.getEntries()
  },
)

Promise-based useConfirmDialog

Source: https://vueuse.org/core/useconfirmdialog

This example demonstrates using useConfirmDialog with promises for asynchronous confirmation flows. The reveal function returns a promise that resolves when the dialog is confirmed or canceled.

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

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

async function 
openDialog
() {
  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>

Passing Arguments to Promise

Source: https://vueuse.org/core/createtemplatepromise

Defining and passing arguments to the start method, accessible via the args property in the template.

import { 
createTemplatePromise
 } from '@vueuse/core'

const 
TemplatePromise
 = 
createTemplatePromise
<boolean, [string, number]>()
import { createTemplatePromise } from '@vueuse/core'
const TemplatePromise = createTemplatePromise()
const 
result
 = await 
TemplatePromise
.
start
('hello', 123) // Pr
'use strict'
const result = await TemplatePromise.start('hello', 123) // Pr
<template>
  <TemplatePromise v-slot="{ 
args
, 
resolve
 }">
    <
div
>{{ 
args
[0] }}</
div
>
    <!-- hello -->
    <
div
>{{ 
args
[1] }}</
div
>
    <!-- 123 -->
    <
button
 @
click
="
resolve
(true)">
      OK
    </
button
>
  </TemplatePromise>
</template>

Basic Usage Output

Source: https://vueuse.org/core/useMouse

Displays the initial state of the mouse position variables.

x: 0
y: 0
sourceType: null

x: 0
y: 0
sourceType: null


useAbs - Reactive Absolute Value

Source: https://vueuse.org/math/useabs

Demonstrates how to use the useAbs composable to get the reactive absolute value of a number.

## useAbs

### Description
Reactive `Math.abs`.

### Method
Composable function

### Endpoint
N/A (Composable function)

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
import { ref } from 'vue'
import { useAbs } from '@vueuse/math'

const value = ref(-23)
const absValue = useAbs(value) // Ref<23>

Response

Success Response (Composable Return)

  • absValue (ComputedRef) - A computed reference containing the absolute value of the input.

Response Example

{
  "absValue": 23
}

Type Declarations

/**
 * Reactive `Math.abs`.
 *
 * @see https://vueuse.org/useAbs
 *
 * @__NO_SIDE_EFFECTS__
 */
export declare function useAbs(value: MaybeRefOrGetter<number>): ComputedRef<number>

--------------------------------

### Use useMin with an array

Source: https://vueuse.org/math/useMin

Import useMin from '@vueuse/math' and pass a ref array to get a reactive minimum value.

```typescript
import {
useMin
} from '@vueuse/math'

const array = ref([1, 2, 3, 4])
const min = useMin(array) // Ref<1>

useStepper with Steps as Object

Source: https://vueuse.org/core/usestepper

This example shows how to use useStepper when steps are defined as an object, allowing for more descriptive step configurations. It illustrates accessing the title property of the current step.

## useStepper with Steps as Object

### Description
This example shows how to use `useStepper` when steps are defined as an object, allowing for more descriptive step configurations. It illustrates accessing the `title` property of the current step.

### Method
`useStepper`

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
None

### Request Example
```typescript
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'

Response

Success Response (200)

Similar to the array-based approach, this composable returns reactive state and methods. When steps are objects, the current computed property will return the full step object.

  • steps (Ref