Collection of essential Vue Composition Utilities
- ⚡ Fully tree shakable: Only take what you want, bundle size
- 🦾 Type Strong: Written in Typescript, with TS Docs
- 🕶 Seamless migration: Works for both Vue 3 and 2
- 🔩 Flexible: Configurable event filters
- 🌎 No bundler required: Usable it via CDN
- 🔋 SSR Friendly
- 🎪 Interactive docs & demos: Check out the Storybook!
- 🔌 Optional Add-ons: Router, Firebase, RxJS, etc.
import { useMouse, usePreferredDark, useLocalStorage } from '@vueuse/core'
export default {
setup() {
// tracks mouse position
const { x, y } = useMouse()
// is user prefers dark theme
const isDark = usePreferredDark()
// persist state in localStorage
const store = useLocalStorage(
'my-storage',
{
name: 'Apple',
color: 'red',
},
)
return { x, y, isDark, store }
}
})
Refer to functions list or documentations for more details.
🎩 From v4.0, it works for Vue 2 & 3 within a single package by the power of vue-demi!
npm i @vueuse/core
Vue 3 Demo: Vite, Webpack / Vue 2 Demo: Vue CLI
<script src="https://unpkg.com/@vueuse/core"></script>
It will be exposed to global as window.VueUse
You can check out the full documents and live demos in Storybook.
-
Animation
useInterval
— reactive counter increases on every intervaluseIntervalFn
— wrapper forsetInterval
with controlsuseRafFn
— call function on everyrequestAnimationFrame
useTimeout
— update value after a given time with controlsuseTimeoutFn
— wrapper forsetTimeout
with controlsuseTimestamp
— reactive current timestampuseTransition
— transition between values
-
Browser
useBrowserLocation
— reactive browser locationuseClipboard
— reactive Clipboard APIuseCssVar
— manipulate CSS variablesuseEventListener
— use EventListener with easeuseFavicon
— reactive faviconuseFullscreen
— reactive Fullscreen APIuseMediaQuery
— reactive Media QueryusePermission
— reactive Permissions APIusePreferredColorScheme
— reactive prefers-color-scheme media queryusePreferredDark
— reactive dark theme preferenceusePreferredLanguages
— reactive Navigator LanguagesuseShare
— reactive Web Share APIuseTitle
— reactive document title
-
Component
tryOnMounted
— safeonMounted
tryOnUnmounted
— safeonUnmounted
useVModel
— shorthand for v-model binding
-
Misc
useEventSource
— an EventSource or Server-Sent-Events instance opens a persistent connection to an HTTP serveruseWebSocket
— reactive simple WebSocket clientuseWebWorker
— simple Web Workers registration and communicationuseWebWorkerFn
— run expensive function without blocking the UI
-
Sensors
onClickOutside
— listen for clicks outside of an elementonStartTyping
— fires when users start typing on non-editable elementsuseBattery
— reactive Battery Status APIuseDeviceLight
— reactive DeviceLightEventuseDeviceMotion
— reactive DeviceMotionEventuseDeviceOrientation
— reactive DeviceOrientationEventuseDevicePixelRatio
— reactively trackwindow.devicePixelRatio
useDocumentVisibility
— reactively trackdocument.visibilityState
useElementBounding
— reactive bounding box of an HTML elementuseElementSize
— reactive size of an HTML elementuseElementVisibility
— tracks the visibility of an element within the viewportuseGeolocation
— reactive Geolocation APIuseIdle
— tracks whether the user is being inactiveuseIntersectionObserver
— detects that a target element's visibilityuseMouse
— reactive mouse positionuseMouseInElement
— reactive mouse position related to an elementuseMousePressed
— reactive mouse pressing stateuseMutationObserver
— watch for changes being made to the DOM treeuseNetwork
— reactive Network statususeOnline
— reactive online stateusePageLeave
— reactive state to show whether the mouse leaves the pageuseParallax
— create parallax effect easilyuseResizeObserver
— reports changes to the dimensions of an Element's content or the border-boxuseSpeechRecognition
— reactive SpeechRecognitionuseWindowScroll
— reactive window scrolluseWindowSize
— reactive window size
-
State
createGlobalState
— keep states in the global scope to be reusable across Vue instancesuseLocalStorage
— reactive LocalStorageuseSessionStorage
— reactive SessionStorageuseStorage
— reactive LocalStorage/SessionStorage
-
Utilities
asyncComputed
— computed for async functionsbiSyncRef
— two-way refs synchronizationcontrolledComputed
— explicitly define the deps of computedextendRef
— add extra attributes to RefmakeDestructurable
— make isomorphic destructurable for object and array at the same timesyncRef
— keep target refs in sync with a source refuseAsyncState
— reactive async stateuseCounter
— basic counter with utility functionsuseDebounce
— debounce execution of a ref valueuseDebounceFn
— debounce execution of a functionuseManualRefHistory
— manually track the change history of a ref when the using callscommit()
useRefHistory
— track the change history of a refuseThrottle
— throttle changing of a ref valueuseThrottleFn
— throttle execution of a functionuseToggle
— a boolean switcher with utility functions
-
Watch
debouncedWatch
— debounced watchignorableWatch
— ignorable watchpausableWatch
— pausable watchthrottledWatch
— throttled watchwatchWithFilter
—watch
with additional EventFilter controlwhen
— promised one-time watch for ref changes
More functions to be added. Please stay tuned. (PRs are also welcome!)
Meanwhile, try also vue-composable by @pikax!
The core package aims to be lightweight and dependence free. While the add-ons are wrapping popular packages into the consistent API style.
-
Router (
@vueuse/router
) - Utilities for vue-routeruseRouteHash
— shorthand for reactive route.hashuseRouteQuery
— shorthand for reactive route.query
-
Integrations (
@vueuse/integrations
) - Integration wrappers for utility librariesuseAxios
— wrapper foraxios
useCookies
— wrapper foruniversal-cookie
useNProgress
— reactive wrapper fornprogress
useQRCode
— wrapper forqrcode
-
RxJS (
@vueuse/rxjs
) - Enables RxJS reactive functions in Vuefrom
— two wrappers around of the original functions to allow use ref objectstoObserver
— sugar function to convert a ref in an observeruseObservable
— use an ObservableuseSubscription
— uses subscriptions without worry about unsubscribing to it or memory leaks
-
Firebase (
@vueuse/firebase
) - Enables realtime bindings for FirebaseuseFirestore
— reactive Firestore bindinguseRTDB
— reactive Firebase Realtime Database binding
See the Contributing Guide
This project is heavily inspired by the following awesome projects.
- streamich/react-use
- u3u/vue-hooks
- shuidi-fed/vue-composition-toolkit
- logaretm/vue-use-web
- kripod/react-hooks
Thanks!
This project exists thanks to all the people who contribute. How to Contribute.
Become a financial contributor and help us sustain our community. Contribute via Open Collective
Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]
MIT License © 2019-2020 Anthony Fu