### Complete Setup Example with Script and Template Source: https://vueuse.nodejs.cn/core/createTemplatePromise Full working example demonstrating createTemplatePromise usage with script setup, v-slot binding, and async function calling the start method to open a promise-based dialog. ```vue ``` -------------------------------- ### Install VueUse Core and Components Source: https://vueuse.nodejs.cn/guide/components Installs the core VueUse library and the components package using npm. This is the initial setup step required to use the renderless components. ```bash npm i @vueuse/core @vueuse/components ``` -------------------------------- ### Basic JavaScript Setup Source: https://vueuse.nodejs.cn/integrations/useAsyncValidator An empty JavaScript file setup, often used as a placeholder or starting point for integrating VueUse composables in a JavaScript-based Vue project. This file is typically part of a larger application structure. ```javascript export {} ``` -------------------------------- ### VueUse Usage Example Source: https://vueuse.nodejs.cn/guide Demonstrates importing and using various VueUse functions like `useLocalStorage`, `useMouse`, and `usePreferredDark` within a Vue component's script setup. ```vue ``` -------------------------------- ### Use Gamepad API with Vue Source: https://vueuse.nodejs.cn/core/useGamepad This example demonstrates how to use the `useGamepad` composable to get reactive bindings for gamepad information, including checking support and accessing gamepad details. It requires `@vueuse/core` and `vue`. ```vue ``` -------------------------------- ### Install useQRCode Integration Source: https://vueuse.nodejs.cn/integrations/useQRCode This command installs the `qrcode` library, which is a peer dependency for the `useQRCode` composable. Ensure you have a compatible version installed. ```bash npm i qrcode@^1 ``` -------------------------------- ### Vue Composition API Example using VueUse useCookies Source: https://vueuse.nodejs.cn/integrations/useCookies Demonstrates common usage of the useCookies function within a Vue 3 setup script. It shows how to initialize cookies, get, set, and display cookie values, and retrieve all cookies. This example uses explicit import for useCookies. ```vue ``` -------------------------------- ### useCounter Initialization with Options Source: https://vueuse.nodejs.cn/shared/useCounter Shows how to use the useCounter composable with initial value and options, specifically setting minimum and maximum bounds for the counter. The example imports the function and destructures the returned values, then initializes useCounter with a starting value and configuration. ```typescript import { useCounter } from '@vueuse/core' const { count , inc , dec , set , reset } = useCounter (1, { min : 0, max : 16 }) ``` -------------------------------- ### 原生 ref 用法 - Vue ``` -------------------------------- ### Install useDrauu with npm Source: https://vueuse.nodejs.cn/integrations/useDrauu This command installs the drauu package version 0 or higher using npm. It is a prerequisite for using the useDrauu composable. ```bash npm i drauu@^0 ``` -------------------------------- ### Basic useShare Setup and Share Functionality (TypeScript) Source: https://vueuse.nodejs.cn/core/useShare Demonstrates the basic setup for useShare, including importing the function, destructuring share and isSupported, and calling share with basic options like title, text, and URL. The share method must be called after a user gesture. ```typescript import { useShare } from '@vueuse/core' const { share, isSupported } = useShare () function startShare () { share ({ title : 'Hello', text : 'Hello my friend!', url : location . href , }) } ``` -------------------------------- ### usePageLeave Output Example Source: https://vueuse.nodejs.cn/core/usePageLeave An example JSON output representing the reactive state returned by the usePageLeave composable. It shows the initial state where the mouse has not left the page. ```json { "isLeft": false } ``` -------------------------------- ### Install focus-trap Source: https://vueuse.nodejs.cn/integrations/useFocusTrap 使用 npm 安装 `focus-trap` 库。此库是 `useFocusTrap` 功能的依赖项。 ```bash npm i focus-trap@^7 ``` -------------------------------- ### Install change-case for VueUse Source: https://vueuse.nodejs.cn/integrations/useChangeCase This snippet shows how to install the 'change-case' package, which is a dependency for the useChangeCase composable in VueUse. Ensure you have version 5 or higher. ```bash npm i change-case@^5 ``` -------------------------------- ### Install async-validator with npm Source: https://vueuse.nodejs.cn/integrations/useAsyncValidator This snippet shows how to install the async-validator package, a dependency for useAsyncValidator, using npm. Ensure you have Node.js and npm installed to run this command. ```bash npm i async-validator@^4 ``` -------------------------------- ### useMouse 基本用法 (TypeScript) Source: https://vueuse.nodejs.cn/core/useMouse 演示了 useMouse 的基本用法,用于获取鼠标的 X 和 Y 坐标以及事件来源类型。默认情况下,它同时支持鼠标和触摸事件。此代码片段展示了如何在 setup 函数中导入和使用 useMouse。 ```typescript import { useMouse } from '@vueuse/core' const { x, y, sourceType } = useMouse () ``` -------------------------------- ### Install @vueuse/integrations Package Source: https://vueuse.nodejs.cn/integrations/README Install the @vueuse/integrations package via npm. This add-on provides integration wrappers for various utility libraries that work seamlessly with Vue.js applications. ```bash npm i @vueuse/integrations ``` -------------------------------- ### Call Start Method to Render and Await Promise Resolution Source: https://vueuse.nodejs.cn/core/createTemplatePromise Use the start method to trigger rendering of the template slot and await the promise resolution. Returns the value passed to resolve or reject function. ```typescript async function open() { const result = await TemplatePromise.start() // button is clicked, result is 'ok' } ``` -------------------------------- ### VueUse computedEager Usage Example Source: https://vueuse.nodejs.cn/shared/computedEager Demonstrates the usage of `computedEager` to create a computed property that updates eagerly. It shows how to import `computedEager` and a `ref`, and how the computed property `hasOpenTodos` reacts immediately to changes in the `todos` ref. The example logs the initial and updated states of `hasOpenTodos`. ```typescript import { computedEager } from '@vueuse/core' const todos = ref([]) const hasOpenTodos = computedEager(() => !!todos.length) console.log(hasOpenTodos.value) // false toTodos.value.push({ title: 'Learn Vue' }) console.log(hasOpenTodos.value) // true ``` -------------------------------- ### useMouse 组件用法 (Vue SFC) Source: https://vueuse.nodejs.cn/core/useMouse 展示了如何在 Vue.js 单文件组件 (SFC) 中使用 `UseMouse` 组件。通过插槽 props 访问 `x` 和 `y` 坐标。这种方式无需在 `setup` 函数中显式调用 `useMouse`。 ```vue ``` -------------------------------- ### 在 Vue 组件中使用 createEventHook 函数 Source: https://vueuse.nodejs.cn/shared/createEventHook 演示了如何在 Vue 3 的 ``` -------------------------------- ### Basic useAnimate Setup with Vue 3 Composition API Source: https://vueuse.nodejs.cn/core/useAnimate Demonstrates basic usage of useAnimate composable with Vue 3's setup syntax. The function accepts a template reference to a DOM element, keyframe configuration object, and duration in milliseconds. Returns control functions and state properties for animation management. ```vue ``` -------------------------------- ### 在 Vue 组件中使用全局状态 - TypeScript Source: https://vueuse.nodejs.cn/shared/createGlobalState 演示如何在 Vue 组件的 setup 函数中导入和使用全局状态。通过调用导出的 useGlobalState 函数获取全局状态对象,并在模板中使用。 ```typescript // component.ts import { useGlobalState } from './store' export default defineComponent({ setup() { const state = useGlobalState() return { state } }, }) ``` -------------------------------- ### useCountdown 动态更新与重置 - TypeScript Source: https://vueuse.nodejs.cn/core/useCountdown 演示了如何使用 ref 来动态更改 useCountdown 的初始倒计时值。同时展示了 start() 和 resume() 方法可以接受新的倒计时值,以及 reset() 方法用于重置倒计时到指定值而不启动。依赖 @vueuse/core 和 vue 的 shallowRef。输入为可变倒计时值,输出为 start, reset 函数。 ```typescript import { useCountdown } from '@vueuse/core' import { shallowRef } from 'vue' const countdown = shallowRef (5) const { start, reset } = useCountdown ( countdown, { }) // change the countdown value countdown .value = 10 // start a new countdown with 2 seconds start (2) // reset the countdown to 4, but do not start it reset (4) // start the countdown with the current value of `countdown` start () ``` -------------------------------- ### Use Document Visibility with Script Setup (Vue) Source: https://vueuse.nodejs.cn/core/useDocumentVisibility Demonstrates how to use the `useDocumentVisibility` composable within a Vue ` ``` -------------------------------- ### 使用 useTextSelection 跟踪文本选择 (Vue) Source: https://vueuse.nodejs.cn/core/useTextSelection 此代码段演示了如何在 Vue.js 应用程序中使用 `useTextSelection` 函数来反应式地获取用户选中的文本。它导入了必要的函数,并在 ` ``` -------------------------------- ### Options API v-model 绑定使用 useVModels Source: https://vueuse.nodejs.cn/core/useVModels 在 Options API 中使用 useVModels 来处理 props 的 v-model 绑定。在 setup 函数中调用 useVModels,并将返回的对象解构出来。你可以直接访问和修改这些响应式属性,它们会自动触发相应的 emit 事件。 ```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') }, } ``` -------------------------------- ### useActiveElement 组合式函数基础用法 - Vue 3 Source: https://vueuse.nodejs.cn/core/useActiveElement 在 Vue 3 Script Setup 中导入并使用 useActiveElement 函数。该函数返回一个反应式引用,包含当前获得焦点的 DOM 元素。通过 watch 监听其变化以捕获焦点事件。 ```typescript ``` -------------------------------- ### useOffsetPagination Composable Setup with JavaScript Source: https://vueuse.nodejs.cn/core/useOffsetPagination Import and configure the useOffsetPagination composable from @vueuse/core using JavaScript. Defines a fetchData callback for handling pagination changes and destructures the returned pagination state object. ```javascript import { useOffsetPagination } from '@vueuse/core' function fetchData({ currentPage, currentPageSize }) { fetch(currentPage, currentPageSize).then((responseData) => { data.value = responseData }) } const { currentPage, currentPageSize, pageCount, isFirstPage, isLastPage, prev, next, } = useOffsetPagination({ total: database.value.length, page: 1, pageSize: 10, onPageChange: fetchData, onPageSizeChange: fetchData, }) ``` -------------------------------- ### Vue.js useAuth with Firebase Authentication Example Source: https://vueuse.nodejs.cn/firebase/useAuth This example demonstrates how to use the `useAuth` composable from VueUse to integrate reactive Firebase authentication into a Vue.js application. It shows the setup for initializing Firebase, obtaining authentication instance, and using `useAuth` to get reactive `isAuthenticated` and `user` states. It also includes a function to handle Google Sign-In using `signInWithPopup` and displays conditional UI based on the authentication status. ```vue ``` -------------------------------- ### Use VueUse in Nuxt Application Source: https://vueuse.nodejs.cn/guide Example of using VueUse composables like `useMouse` within a Nuxt 3 application's script setup. The module enables auto-importing. ```vue ``` -------------------------------- ### Global Dependencies Configuration - Testing with Mock Window Source: https://vueuse.nodejs.cn/guide/config Demonstrates using configurable global dependencies for testing VueUse functions with mock objects. Pass a mockWindow object to replace the default global window instance, enabling unit tests without relying on actual browser APIs. ```TypeScript // testing const mockWindow = { /* ... */ } const { x, y } = useMouse({ window: mockWindow }) ``` -------------------------------- ### Use useScreenSafeArea Composable - TypeScript Source: https://vueuse.nodejs.cn/core/useScreenSafeArea This TypeScript example shows how to import and use the `useScreenSafeArea` composable to get reactive safe area inset values (top, right, bottom, left) within a Vue component. ```typescript import { useScreenSafeArea } from '@vueuse/core' const { top, right, bottom, left, } = useScreenSafeArea() ``` -------------------------------- ### Use Speech Recognition in Vue.js Source: https://vueuse.nodejs.cn/core/useSpeechRecognition This example demonstrates how to import and use the `useSpeechRecognition` composable from '@vueuse/core' in a Vue.js application. It exposes reactive states like `isSupported`, `isListening`, `isFinal`, and `result`, along with functions to `start` and `stop` the recognition. ```typescript import { useSpeechRecognition } from '@vueuse/core' const { isSupported , isListening , isFinal , result , start , stop , } = useSpeechRecognition () ``` -------------------------------- ### Basic useFetch Usage in TypeScript Source: https://vueuse.nodejs.cn/core/useFetch Demonstrates the fundamental usage of the useFetch function, initializing a request with a URL and accessing fetching status, errors, and data. ```typescript import { useFetch } from '@vueuse/core' const { isFetching , error , data } = useFetch (url) ``` -------------------------------- ### Vue.js: Use UseElementSize Component Source: https://vueuse.nodejs.cn/core/useElementSize This example shows how to use the `UseElementSize` component provided by VueUse. It exposes the `width` and `height` of its slot content reactively. This is a convenient way to get element sizes without explicit template refs. ```vue ``` -------------------------------- ### Destructure props object with toRefs and useVModel Source: https://vueuse.nodejs.cn/shared/toRefs Vue component example showing how to use toRefs with useVModel for destructuring and reactively binding props in a setup function. Demonstrates bidirectional data binding where modifying destructured refs emits updates to parent component. ```Vue ``` -------------------------------- ### Vue.js: Use useElementSize with Template Refs Source: https://vueuse.nodejs.cn/core/useElementSize This snippet demonstrates how to use the `useElementSize` composable in Vue.js with ` ``` -------------------------------- ### Vue: Use onStartTyping to Focus Input on Typing Source: https://vueuse.nodejs.cn/core/onStartTyping This Vue example demonstrates how to use the onStartTyping composable to automatically focus an input field when the user begins typing. It utilizes `useTemplateRef` to get a reference to the input element and `onStartTyping` to trigger the focus action. ```vue ``` -------------------------------- ### Import and Initialize useFullscreen (TypeScript) Source: https://vueuse.nodejs.cn/core/useFullscreen Demonstrates how to import and initialize the useFullscreen composable in TypeScript. It provides access to reactive state like `isFullscreen` and control functions such as `enter`, `exit`, and `toggle`. No specific dependencies are required beyond VueUse itself. ```typescript import { useFullscreen } from '@vueuse/core' const { isFullscreen , enter , exit , toggle } = useFullscreen () ``` -------------------------------- ### Vue Composition API with useCookies options (TypeScript) Source: https://vueuse.nodejs.cn/integrations/useCookies Shows how to access and modify cookies using the Composition API with advanced options. This example demonstrates setting 'doNotParse' and 'autoUpdateDependencies' options, and accessing methods like get, getAll, set, remove, and change listeners. ```typescript const { get , getAll , set , remove , addChangeListener , removeChangeListener } = useCookies (['cookie-name'], { doNotParse : false, autoUpdateDependencies : false }) ``` -------------------------------- ### Import and use useDevicePixelRatio composable Source: https://vueuse.nodejs.cn/core/useDevicePixelRatio Import the useDevicePixelRatio composable from @vueuse/core and destructure the pixelRatio reactive value. This provides real-time tracking of the device pixel ratio, which updates when zooming in/out or moving windows between screens with different scaling factors. ```typescript import { useDevicePixelRatio } from '@vueuse/core' const { pixelRatio } = useDevicePixelRatio() ``` -------------------------------- ### VueUse vResizeObserver Directive Usage Source: https://vueuse.nodejs.cn/core/useResizeObserver This example shows how to use the v-resize-observer directive provided by VueUse components. It attaches an event handler to the element that gets called whenever the element's size changes, updating a reactive text variable with the new dimensions. This approach simplifies the integration for directive-based usage. ```vue ``` -------------------------------- ### Get Element Ref for Specific Vue Component with VueUse Source: https://vueuse.nodejs.cn/core/useCurrentElement This example shows how to use `useCurrentElement` with a specific Vue component reference. It involves using `shallowRef` to create a reference to the target component and then passing this reference to `useCurrentElement`. This is useful for targeting elements within child components. The element ref will be `undefined` until the component is mounted. ```vue ``` -------------------------------- ### 自定义事件目标 - VueUse Source: https://vueuse.nodejs.cn/core/onKeyStroke 通过 options 对象中的 `target` 属性,可以指定 onKeyStroke 监听事件的目标。默认情况下,它监听 `document`。此示例演示了如何将监听目标设置为 `document`。 ```typescript onKeyStroke ('A', (e) => { console.log('Key A pressed on document') }, { target: document }) ``` -------------------------------- ### usePerformanceObserver 观察性能指标 (JavaScript) Source: https://vueuse.nodejs.cn/core/usePerformanceObserver 使用 usePerformanceObserver 观察性能指标,这里以 'paint' 类型为例。它接收一个配置对象和一个回调函数,回调函数接收性能条目列表并更新 entrys ref。 ```javascript import { usePerformanceObserver } from '@vueuse/core' const entrys = ref([]) usePerformanceObserver( { entryTypes: ['paint'], }, (list) => { entrys.value = list.getEntries() }, ) ``` -------------------------------- ### Basic Usage of useRefHistory with a Counter Source: https://vueuse.nodejs.cn/core/useRefHistory This example demonstrates the basic usage of `useRefHistory` to track changes in a shallow ref counter. It imports necessary functions from `@vueuse/core` and `vue`, initializes a counter, and then uses `useRefHistory` to get the history, undo, and redo functions. The `history` variable will store an array of past states, and `undo`/`redo` allow navigation through these states. ```typescript import { useRefHistory } from '@vueuse/core' import { shallowRef } from 'vue' const counter = shallowRef(0) const { history, undo, redo } = useRefHistory(counter) ``` -------------------------------- ### Initialize and use useFirestore with collections and documents Source: https://vueuse.nodejs.cn/firebase/useFirestore Demonstrates basic setup of useFirestore with Firebase initialization, collection binding, and document reference binding. Shows how to import required dependencies from Firebase and VueUse, initialize the app, and create reactive references to Firestore collections and documents. ```TypeScript import { useFirestore } from '@vueuse/firebase/useFirestore' import { initializeApp } from 'firebase/app' import { collection , doc , getFirestore , limit , orderBy , query } from 'firebase/firestore' import { computed , shallowRef } from 'vue' const app = initializeApp ({ projectId : 'MY PROJECT ID' }) const db = getFirestore ( app ) const todos = useFirestore ( collection ( db , 'todos')) // or for doc reference const user = useFirestore ( doc ( db , 'users', 'my-user-id')) // you can also use ref value for reactive query const postsLimit = shallowRef (10) const postsQuery = computed (() => query ( collection ( db , 'posts'), orderBy ('createdAt', 'desc'), limit ( postsLimit . value ))) const posts = useFirestore ( postsQuery ) // you can use the boolean value to tell a query when it is ready to run // when it gets falsy value, return the initial value const userId = shallowRef ('') const userQuery = computed (() => userId . value && doc ( db , 'users', userId . value )) const userData = useFirestore ( userQuery , null) ``` -------------------------------- ### Install universal-cookie for VueUse useCookies Source: https://vueuse.nodejs.cn/integrations/useCookies This command installs the 'universal-cookie' package, which is a dependency for the useCookies function in VueUse. Ensure you have npm or another package manager installed. ```bash npm i universal-cookie@^7 ``` -------------------------------- ### Simple Virtual List with useVirtualList Source: https://vueuse.nodejs.cn/core/useVirtualList Create a basic virtual list with 99999 items using useVirtualList composable. Requires itemHeight configuration to calculate wrapper element height correctly. Returns list, containerProps, and wrapperProps for rendering. ```typescript import { useVirtualList } from '@vueuse/core' const { list, containerProps, wrapperProps } = useVirtualList( Array.from(Array.from({ length: 99999 }).keys()), { itemHeight: 22 } ) ``` -------------------------------- ### Install sortablejs dependency for useSortable Source: https://vueuse.nodejs.cn/integrations/useSortable Install the sortablejs package as a peer dependency for the useSortable composable. This is required before using useSortable from @vueuse/integrations. ```bash npm i sortablejs@^1 ``` -------------------------------- ### 使用 VueUse CDN Source: https://vueuse.nodejs.cn/guide/index 通过 CDN 引入 VueUse 库,将其暴露为全局变量 `window.VueUse`。适用于快速原型开发或不需要构建工具的项目。 ```html ``` -------------------------------- ### watchOnce 基础用法 - VueUse Source: https://vueuse.nodejs.cn/shared/watchOnce 导入并使用 watchOnce 函数监听源值的变化。当源值改变时,回调函数仅执行一次,之后监视器自动停止。这是 watch 函数配置 { once: true } 选项的简化写法。 ```typescript import { watchOnce } from '@vueuse/core' watchOnce(source, () => { // triggers only once console.log('source changed!') }) ``` -------------------------------- ### Install axios dependency via npm Source: https://vueuse.nodejs.cn/integrations/useAxios Install the axios library version 1.x or higher as a dependency for the useAxios composable. This is required before using the useAxios function from @vueuse/integrations. ```bash npm i axios@^1 ``` -------------------------------- ### Using `whenever` for Shorter Combination Detection (TypeScript) Source: https://vueuse.nodejs.cn/core/useMagicKeys This example illustrates a more concise way to handle key combinations using the `whenever` utility function from '@vueuse/core'. It simplifies the logic for reacting to specific key sequences like 'Shift+Space'. Dependencies include '@vueuse/core'. ```typescript import { useMagicKeys , whenever } from '@vueuse/core' const keys = useMagicKeys () whenever ( keys .shift_space , () => { console . log ('Shift+Space have been pressed') }) ``` -------------------------------- ### Install VueUse Nuxt Module Source: https://vueuse.nodejs.cn/guide Install the VueUse Nuxt module for automatic imports in Nuxt 3 and Nuxt Bridge applications. This can be done via the Nuxt CLI or npm. ```bash npx nuxt@latest module add vueuse ``` ```bash npm i -D @vueuse/nuxt @vueuse/core ``` -------------------------------- ### Install Fuse.js with Yarn Source: https://vueuse.nodejs.cn/integrations/useFuse Install Fuse.js as a peer dependency for the @vueuse/integrations/useFuse composable using yarn. This command ensures that the correct version of Fuse.js is available for the integration to work. ```bash yarn add fuse.js ``` -------------------------------- ### VueUse useMediaQuery Basic Usage (TypeScript) Source: https://vueuse.nodejs.cn/core/useMediaQuery Demonstrates the basic usage of the `useMediaQuery` composable to create reactive boolean values based on CSS media queries. It shows how to check for screen width and color scheme preferences. This requires the `@vueuse/core` package. ```typescript import { useMediaQuery } from '@vueuse/core' const isLargeScreen = useMediaQuery ('(min-width: 1024px)') const isPreferredDark = useMediaQuery ('(prefers-color-scheme: dark)') ``` -------------------------------- ### 安装 @vueuse/rxjs 和 rxjs Source: https://vueuse.nodejs.cn/rxjs/README 使用 npm 或 yarn 安装 @vueuse/rxjs 和 rxjs 包。这是使用该插件的先决条件。 ```bash npm i @vueuse/rxjs rxjs ``` -------------------------------- ### Install Fuse.js with NPM Source: https://vueuse.nodejs.cn/integrations/useFuse Install Fuse.js as a peer dependency for the @vueuse/integrations/useFuse composable using npm. This command ensures that the correct version of Fuse.js is available for the integration to work. ```bash npm install fuse.js@^7 ``` -------------------------------- ### 使用可配置的全局变量 (VueUse) Source: https://vueuse.nodejs.cn/guidelines 在处理像 `window` 或 `document` 这样的全局变量时,可以使用 `configurableWindow` 或 `configurableDocument` 选项接口,以提高在多窗口、测试模拟和 SSR 等场景下的灵活性。此 `useActiveElement` 函数展示了如何配置 `window`。 ```typescript import type { ConfigurableWindow } from '../_configurable' import { defaultWindow } from '../_configurable' import { useEventListener } from '../useEventListener' export function useActiveElement( options: ConfigurableWindow = {}, ) { const { // defaultWindow = isClient ? window : undefined window = defaultWindow, } = options let el: T // skip when in Node.js environment (SSR) if (window) { useEventListener(window, 'blur', () => { el = window?.document.activeElement }, true) } /* ... */ } ``` ```typescript // in iframe and bind to the parent window useActiveElement({ window: window.parent }) ``` -------------------------------- ### 使用 reactify 包装自定义函数实现反应式勾股定理 Source: https://vueuse.nodejs.cn/shared/reactify 此示例展示了另一种实现反应式勾股定理的方法。首先定义一个普通的 `pythagorean` 函数,然后使用 `reactify` 将其转换为反应式函数。这种方式更加直接,适用于已经定义好的普通函数。 ```typescript import { reactify } from '@vueuse/core' import { shallowRef } from 'vue' function pythagorean ( a : number, b : number) { return Math . sqrt ( a ** 2 + b ** 2) } const a = shallowRef (3) const b = shallowRef (4) const c = reactify ( pythagorean )( a , b ) console . log ( c . value ) // 5 ``` ```javascript import { reactify } from '@vueuse/core' import { shallowRef } from 'vue' function pythagorean(a, b) { return Math.sqrt(a ** 2 + b ** 2) } const a = shallowRef(3) const b = shallowRef(4) const c = reactify(pythagorean)(a, b) console.log(c.value) // 5 ``` -------------------------------- ### useCountdown 基础用法 - TypeScript Source: https://vueuse.nodejs.cn/core/useCountdown 展示了 useCountdown 的基本用法,通过传入一个初始秒数来创建一个倒计时。提供了 start, stop, pause, resume 方法来控制倒计时,并在 onComplete 和 onTick 回调中处理倒计时完成和 tick 事件。依赖 @vueuse/core。输入为初始秒数,输出为 remaining, start, stop, pause, resume 函数。 ```typescript import { useCountdown } from '@vueuse/core' const countdownSeconds = 5 const { remaining, start, stop, pause, resume } = useCountdown ( countdownSeconds, { onComplete() { }, onTick() { } }) ``` -------------------------------- ### useMouse 仅检测鼠标移动 (TypeScript) Source: https://vueuse.nodejs.cn/core/useMouse 展示了如何配置 useMouse 以仅检测鼠标事件,忽略触摸事件。通过设置 `touch` 选项为 `false` 来实现。适用于只需要在用户使用鼠标时跟踪位置的场景。 ```typescript const { x, y } = useMouse ({ touch: false }) ``` -------------------------------- ### refAutoReset Usage Example (TypeScript) Source: https://vueuse.nodejs.cn/shared/refAutoReset Demonstrates how to use the `refAutoReset` composable from VueUse. It creates a ref that automatically reverts to its default value after 1000 milliseconds. The example shows how to set a new value and explains that it will revert automatically. ```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' } ``` -------------------------------- ### VueUse useRouteQuery Usage Example Source: https://vueuse.nodejs.cn/router/useRouteQuery Demonstrates how to use the `useRouteQuery` function to access and set reactive route query parameters. It shows examples with and without default values, as well as with value transformation. The function is part of the @vueuse/router add-on. ```typescript 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' } }) ``` -------------------------------- ### Pass watch options to useExtractedObservable (TypeScript/JavaScript) Source: https://vueuse.nodejs.cn/rxjs/useExtractedObservable This example shows how to pass standard Vue `watch` options as the last argument to `useExtractedObservable`. This allows you to control the behavior of the underlying watcher, such as setting `immediate: false`. It includes examples in both TypeScript and JavaScript. ```typescript import { useExtractedObservable } from '@vueuse/rxjs' import { interval } from 'rxjs' import { mapTo, scan, startWith, takeWhile } from 'rxjs/operators' import { shallowRef } from 'vue' // setup() const start = shallowRef() const count = useExtractedObservable( start, (start) => { return interval(1000).pipe( mapTo(1), startWith(start), scan((total, next) => next + total), takeWhile(num => num < 10) ) }, {}, { immediate: false } ) ``` ```javascript import { useExtractedObservable } from '@vueuse/rxjs' import { interval } from 'rxjs' import { mapTo, scan, startWith, takeWhile } from 'rxjs/operators' import { shallowRef } from 'vue' // setup() const start = shallowRef() const count = useExtractedObservable( start, (start) => { return interval(1000).pipe( mapTo(1), startWith(start), scan((total, next) => next + total), takeWhile((num) => num < 10), ) }, {}, { immediate: false, }, ) ``` -------------------------------- ### Vue Script Setup: Track Window Focus with useWindowFocus Source: https://vueuse.nodejs.cn/core/useWindowFocus Demonstrates how to use the useWindowFocus composable in Vue's script setup to reactively track if the browser window is focused. It imports the function and uses its boolean return value to display the focus state. ```vue ``` -------------------------------- ### Get Current Element Ref in TypeScript with VueUse Source: https://vueuse.nodejs.cn/core/useCurrentElement This snippet demonstrates how to import and use the `useCurrentElement` composable from `@vueuse/core` in a TypeScript Vue project to get a computed reference to the current component's DOM element. The returned ref will be `undefined` until the component is mounted. ```typescript import { useCurrentElement } from '@vueuse/core' const el = useCurrentElement () ``` -------------------------------- ### transition: 手动执行和取消过渡 (TypeScript) Source: https://vueuse.nodejs.cn/core/useTransition 展示了如何使用 `transition` 函数手动执行过渡,并返回一个在过渡完成时解析的 Promise。通过定义 `abort` 函数,可以根据条件取消手动进行的过渡。 ```typescript import { transition } from '@vueuse/core' await transition(source, from, to, { abort() { if (shouldAbort) return true } }) ``` -------------------------------- ### 安装 VueUse (npm) Source: https://vueuse.nodejs.cn/guide/index 使用 npm 安装 VueUse 核心库。这是在 Vue 项目中最常用的安装方式。 ```bash npm i @vueuse/core ``` -------------------------------- ### watchImmediate - 创建响应式值监视器 Source: https://vueuse.nodejs.cn/shared/watchImmediate watchImmediate 是对 watch 函数的简写,自动启用 immediate 选项。当监视创建时会立即执行回调函数一次,然后在被监视的值发生变化时继续执行。适用于需要在初始化时立即处理值的场景,如数据加载、初始化计算等。 ```typescript import { watchImmediate } from '@vueuse/core' const obj = ref('vue-use') // changing the value from some external store/composables obj.value = 'VueUse' watchImmediate(obj, (updated) => { console.log(updated) // Console.log will be logged twice }) ``` -------------------------------- ### useParallax Vue Composition Setup Source: https://vueuse.nodejs.cn/core/useParallax Basic setup for using the useParallax composable in a Vue component with TypeScript. The function accepts a container reference and returns tilt, roll, and source properties. Tilt and roll values range from -1 to 1 representing device/mouse orientation angles. ```vue ``` -------------------------------- ### useCycleList - 循环浏览列表项目的基础用法 Source: https://vueuse.nodejs.cn/core/useCycleList 展示如何从 @vueuse/core 导入 useCycleList,初始化一个包含多个项目的列表,并通过 next()、prev() 和 go() 方法在列表中循环浏览。state.value 存储当前选中项目,支持向前、向后和直接跳转到指定索引位置。 ```typescript import { useCycleList } from '@vueuse/core' const { state, next, prev, go } = useCycleList([ 'Dog', 'Cat', 'Lizard', 'Shark', 'Whale', 'Dolphin', 'Octopus', 'Seal', ]) console.log(state.value) // 'Dog' prev() console.log(state.value) // 'Seal' go(3) console.log(state.value) // 'Shark' ```