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 LanguagesuseScriptTag
โ script tag injectinguseShare
โ reactive Web Share APIuseTitle
โ reactive document titleuseUrlSearchParams
โ reactive URLSearchParams
-
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 Refget
โ shorthand for accessingref.value
makeDestructurable
โ make isomorphic destructurable for object and array at the same timereactify
โ converts plain function into a reactive functionreactifyObject
โ applyreactify
to an objectset
โ shorthand forref.value = x
syncRef
โ 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