Vue.js course ยท Module 9: Composables & VueUse
VueUse - Composables Library
In this lesson8
VueUse is a collection of 200+ ready-made composables - like the NOVA LAB library of standard research protocols! Why do you need such a library? Every project brings back the same tasks: remember settings in localStorage, track the window size, the mouse position or dark mode, delay a search until the user stops typing. Each of them requires listening to browser events and cleaning up afterwards. You can write all that from scratch in every project, or reach for proven, tested functions from the @vueuse/core package. Only the functions you actually import end up in the application bundle.
Installing VueUse
You install the library like any npm package. The current version of VueUse requires Vue 3.5 or newer:
npm install @vueuse/coreAfter installation you import individual functions from '@vueuse/core', exactly like ref or computed from 'vue'. No plugin registration is needed.
useLocalStorage
The first protocol saves the lab settings so that they survive a page refresh. useLocalStorage takes a key and a default value, and returns a ref synchronized with the browser's localStorage:
<script setup>
import { useLocalStorage } from '@vueuse/core'
// Automatically syncs with localStorage
const labSettings = useLocalStorage('lab-settings', {
mode: 'exploration',
sensorsPerView: 12,
sortBy: 'temperature'
})
// Changes are automatically saved to localStorage
labSettings.value.mode = 'research'
</script>
<template>
<div>
<p>Mode: {{ labSettings.mode }}</p>
<button @click="labSettings.mode = 'maintenance'">
Change mode
</button>
</div>
</template>The default value is used only when nothing is stored under the lab-settings key yet. Objects are saved as JSON, and a change to a single field is saved too, because VueUse watches the object deeply.
useMouseInElement
This composable tracks the mouse relative to a specific element. Among other things it returns elementX and elementY, the position measured from the element's top-left corner, and isOutside, which tells you whether the cursor is outside it. The plain x and y are coordinates on the whole page:
<script setup>
import { ref } from 'vue'
import { useMouseInElement } from '@vueuse/core'
const sensorPanel = ref(null)
const { elementX, elementY, isOutside } = useMouseInElement(sensorPanel)
</script>
<template>
<div ref="sensorPanel" class="sensor-panel">
<img src="/sensor-display.jpg" />
<div v-if="!isOutside" class="tooltip" :style="{ left: elementX + 'px', top: elementY + 'px' }">
Position: {{ elementX }}, {{ elementY }}
</div>
</div>
</template>The sensorPanel ref connects to the element through the ref attribute; since Vue 3.5 you can also use useTemplateRef('sensorPanel'). For the tooltip to follow the cursor, the panel needs position: relative in CSS and the tooltip position: absolute.
useIntersectionObserver
The next protocol checks whether an element is visible in the browser window. It is the basis of lazy-loading images and of animations triggered by scrolling. The callback receives a list of observed entries, and the isIntersecting field tells you whether the element has entered the viewport:
<script setup>
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
const experimentPanel = ref(null)
const isVisible = ref(false)
useIntersectionObserver(
experimentPanel,
([{ isIntersecting }]) => {
isVisible.value = isIntersecting
}
)
</script>
<template>
<div ref="experimentPanel">
<Transition name="fade">
<img v-if="isVisible" src="/experiment-data.jpg" />
</Transition>
</div>
</template>The image is downloaded only when the panel appears on screen. VueUse disconnects the observer by itself when the component unmounts, so you don't have to write your own cleanup.
useWindowSize
useWindowSize returns the window's reactive width and height, which update every time the window is resized. From them it's easy to derive view breakpoints with computed:
<script setup>
import { useWindowSize } from '@vueuse/core'
import { computed } from 'vue'
const { width, height } = useWindowSize()
const isMobile = computed(() => width.value < 768)
const isTablet = computed(() => width.value >= 768 && width.value < 1024)
const isDesktop = computed(() => width.value >= 1024)
</script>
<template>
<div>
<p v-if="isMobile">Mobile view</p>
<p v-else-if="isTablet">Tablet view</p>
<p v-else>Desktop view</p>
<p>Dimensions: {{ width }} x {{ height }}</p>
</div>
</template>The template switches the message without any manual resize listener. If you have more breakpoints, VueUse offers the specialized useBreakpoints for that.
useDark & useToggle
useDark returns a ref with the boolean value of dark mode. By default it starts from the system setting, adds the dark class to the <html> element and remembers the choice in localStorage. useToggle turns such a ref into a toggle function:
<script setup>
import { useDark, useToggle } from '@vueuse/core'
const isDark = useDark()
const toggleDark = useToggle(isDark)
</script>
<template>
<div :class="{ dark: isDark }">
<button @click="toggleDark()">
{{ isDark ? 'Light' : 'Dark' }} theme
</button>
</div>
</template>
<style>
body {
transition: background 0.3s, color 0.3s;
}
.dark {
background: #1a1a1a;
color: #f5f5f5;
}
</style>After a click, the dark class appears on <html> and on the div with the :class binding. The binding isn't necessary, because useDark itself adds the class to <html>; we keep it to make it visible where the style comes from.
refDebounced and refThrottled
Debounce waits until a value stops changing for a given time, while throttle lets a change through at most once per interval. In VueUse this is done by refDebounced and refThrottled, which return a delayed copy of a ref. The older names useDebounce and useThrottle still work, but they are marked as deprecated:
<script setup>
import { ref } from 'vue'
import { refDebounced, refThrottled } from '@vueuse/core'
// Debounce - waits until the user stops typing
const searchQuery = ref('')
const debouncedQuery = refDebounced(searchQuery, 500)
// Throttle - at most once every X ms
const scrollPosition = ref(0)
const throttledScroll = refThrottled(scrollPosition, 100)
</script>
<template>
<input v-model="searchQuery" placeholder="Search..." />
<p>Searching: {{ debouncedQuery }}</p>
</template>When you type "oxy", debouncedQuery changes only half a second after the last key, so the request to the server goes out once instead of three times. You would update scrollPosition in a scroll handler. For delaying function calls, VueUse also has useDebounceFn and useThrottleFn.
Popular Composables from VueUse
Finally, a cheat sheet with the functions you will reach for most often:
| Composable | Description |
|---|---|
useLocalStorage | Reactive localStorage |
useFetch | Fetch with reactivity |
useIntersectionObserver | Visibility detection |
useMouseInElement | Mouse position in element |
useWindowSize | Window size |
useDark | Dark mode |
refDebounced | Delayed reactivity (debounce) |
useClipboard | Copy to clipboard |
My advice: before you write your own composable for a browser feature, check vueuse.org. If the function is already there, you get code with tests and correct cleanup. In the editor below you will see what such a composable looks like inside: useConnectionMonitor starts its timers in onMounted and cleans them up in onUnmounted - exactly the work VueUse does for you.
Remember: VueUse is a warehouse of ready-made station protocols - before you build a new instrument, check whether it is already on the shelf.
Code for this lesson: App.vue
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
// Composable with lifecycle hooks: useConnectionMonitor
function useConnectionMonitor(serverUrl) {
const isConnected = ref(false)
const connectionTime = ref(null)
const disconnectionTime = ref(null)
const reconnectAttempts = ref(0)
const latency = ref(0)
const messages = ref([])
let intervalId = null
let connectionCheckId = null
function addMessage(type, text) {
messages.value.unshift({
id: Date.now(),
type,
text,
timestamp: new Date().toLocaleTimeString()
})
if (messages.value.length > 10) {
messages.value.pop()
}
}
function connect() {
isConnected.value = true
connectionTime.value = new Date()
reconnectAttempts.value = 0
addMessage('success', `Connected to ${serverUrl}`)
// Simulate latency monitoring
intervalId = setInterval(() => {
latency.value = Math.floor(Math.random() * 100) + 20
}, 2000)
}
function disconnect() {
isConnected.value = false
disconnectionTime.value = new Date()
addMessage('warning', `Disconnected from ${serverUrl}`)
if (intervalId) {
clearInterval(intervalId)
intervalId = null
}
}
function attemptReconnect() {
if (isConnected.value) return
reconnectAttempts.value++
addMessage('info', `Reconnection attempt #${reconnectAttempts.value}`)
setTimeout(() => {
if (reconnectAttempts.value <= 3) {
connect()
addMessage('success', 'Reconnected successfully!')
} else {
addMessage('error', 'Max reconnection attempts reached')
}
}, 1500)
}
// Lifecycle: Mount
onMounted(() => {
addMessage('info', 'Connection monitor initialized')
// Auto-connect on mount
setTimeout(() => {
connect()
}, 1000)
// Simulate random disconnections
connectionCheckId = setInterval(() => {
if (isConnected.value && Math.random() < 0.1) {
addMessage('warning', 'Connection lost - random event')
disconnect()
setTimeout(attemptReconnect, 2000)
}
}, 5000)
})
// Lifecycle: Unmount
onUnmounted(() => {
addMessage('info', 'Connection monitor shutting down')
if (intervalId) clearInterval(intervalId)
if (connectionCheckId) clearInterval(connectionCheckId)
disconnect()
})
return {
isConnected,
connectionTime,
disconnectionTime,
reconnectAttempts,
latency,
messages,
connect,
disconnect,
attemptReconnect
}
}
// Create connection monitors for different servers
const earthConnection = useConnectionMonitor('Earth Command Center')
const marsConnection = useConnectionMonitor('Mars Base Alpha')
const satelliteConnection = useConnectionMonitor('Orbital Satellite')
</script>
<template>
<div class="connection-lab">
<div class="header">
<h1>Connection Monitor - NOVA LAB</h1>
<p class="subtitle">Module 3: Composables with Lifecycle Hooks</p>
</div>
<div class="connections-grid">
<!-- Earth Connection -->
<div class="connection-card" :class="{ connected: earthConnection.isConnected }">
<div class="connection-header">
<h3>Earth Command</h3>
<div class="status-indicator" :class="{ active: earthConnection.isConnected }">
{{ earthConnection.isConnected ? 'ONLINE' : 'OFFLINE' }}
</div>
</div>
<div class="connection-stats">
<div class="stat-item">
<span class="stat-label">Latency:</span>
<span class="stat-value" :class="{ good: earthConnection.latency < 50 }">
{{ earthConnection.latency }}ms
</span>
</div>
<div class="stat-item">
<span class="stat-label">Reconnect Attempts:</span>
<span class="stat-value">{{ earthConnection.reconnectAttempts }}</span>
</div>
</div>
<div class="connection-times">
<div v-if="earthConnection.connectionTime" class="time-info">
Connected: {{ earthConnection.connectionTime.toLocaleTimeString() }}
</div>
<div v-if="earthConnection.disconnectionTime" class="time-info">
Disconnected: {{ earthConnection.disconnectionTime.toLocaleTimeString() }}
</div>
</div>
<div class="connection-controls">
<button
@click="earthConnection.connect"
:disabled="earthConnection.isConnected"
class="btn btn-success"
>
Connect
</button>
<button
@click="earthConnection.disconnect"
:disabled="!earthConnection.isConnected"
class="btn btn-danger"
>
Disconnect
</button>
<button
@click="earthConnection.attemptReconnect"
:disabled="earthConnection.isConnected"
class="btn btn-warning"
>
Reconnect
</button>
</div>
<div class="messages-log">
<div
v-for="msg in earthConnection.messages.slice(0, 5)"
:key="msg.id"
class="log-message"
:class="'msg-' + msg.type"
>
<span class="msg-time">{{ msg.timestamp }}</span>
<span class="msg-text">{{ msg.text }}</span>
</div>
</div>
</div>
<!-- Mars Connection -->
<div class="connection-card" :class="{ connected: marsConnection.isConnected }">
<div class="connection-header">
<h3>Mars Base Alpha</h3>
<div class="status-indicator" :class="{ active: marsConnection.isConnected }">
{{ marsConnection.isConnected ? 'ONLINE' : 'OFFLINE' }}
</div>
</div>
<div class="connection-stats">
<div class="stat-item">
<span class="stat-label">Latency:</span>
<span class="stat-value" :class="{ good: marsConnection.latency < 50 }">
{{ marsConnection.latency }}ms
</span>
</div>
<div class="stat-item">
<span class="stat-label">Reconnect Attempts:</span>
<span class="stat-value">{{ marsConnection.reconnectAttempts }}</span>
</div>
</div>
<div class="connection-times">
<div v-if="marsConnection.connectionTime" class="time-info">
Connected: {{ marsConnection.connectionTime.toLocaleTimeString() }}
</div>
<div v-if="marsConnection.disconnectionTime" class="time-info">
Disconnected: {{ marsConnection.disconnectionTime.toLocaleTimeString() }}
</div>
</div>
<div class="connection-controls">
<button
@click="marsConnection.connect"
:disabled="marsConnection.isConnected"
class="btn btn-success"
>
Connect
</button>
<button
@click="marsConnection.disconnect"
:disabled="!marsConnection.isConnected"
class="btn btn-danger"
>
Disconnect
</button>
<button
@click="marsConnection.attemptReconnect"
:disabled="marsConnection.isConnected"
class="btn btn-warning"
>
Reconnect
</button>
</div>
<div class="messages-log">
<div
v-for="msg in marsConnection.messages.slice(0, 5)"
:key="msg.id"
class="log-message"
:class="'msg-' + msg.type"
>
<span class="msg-time">{{ msg.timestamp }}</span>
<span class="msg-text">{{ msg.text }}</span>
</div>
</div>
</div>
<!-- Satellite Connection -->
<div class="connection-card" :class="{ connected: satelliteConnection.isConnected }">
<div class="connection-header">
<h3>Orbital Satellite</h3>
<div class="status-indicator" :class="{ active: satelliteConnection.isConnected }">
{{ satelliteConnection.isConnected ? 'ONLINE' : 'OFFLINE' }}
</div>
</div>
<div class="connection-stats">
<div class="stat-item">
<span class="stat-label">Latency:</span>
<span class="stat-value" :class="{ good: satelliteConnection.latency < 50 }">
{{ satelliteConnection.latency }}ms
</span>
</div>
<div class="stat-item">
<span class="stat-label">Reconnect Attempts:</span>
<span class="stat-value">{{ satelliteConnection.reconnectAttempts }}</span>
</div>
</div>
<div class="connection-times">
<div v-if="satelliteConnection.connectionTime" class="time-info">
Connected: {{ satelliteConnection.connectionTime.toLocaleTimeString() }}
</div>
<div v-if="satelliteConnection.disconnectionTime" class="time-info">
Disconnected: {{ satelliteConnection.disconnectionTime.toLocaleTimeString() }}
</div>
</div>
<div class="connection-controls">
<button
@click="satelliteConnection.connect"
:disabled="satelliteConnection.isConnected"
class="btn btn-success"
>
Connect
</button>
<button
@click="satelliteConnection.disconnect"
:disabled="!satelliteConnection.isConnected"
class="btn btn-danger"
>
Disconnect
</button>
<button
@click="satelliteConnection.attemptReconnect"
:disabled="satelliteConnection.isConnected"
class="btn btn-warning"
>
Reconnect
</button>
</div>
<div class="messages-log">
<div
v-for="msg in satelliteConnection.messages.slice(0, 5)"
:key="msg.id"
class="log-message"
:class="'msg-' + msg.type"
>
<span class="msg-time">{{ msg.timestamp }}</span>
<span class="msg-text">{{ msg.text }}</span>
</div>
</div>
</div>
</div>
<div class="info-panel">
<h3>Lifecycle Hooks in Composables</h3>
<div class="info-content">
<p><strong>useConnectionMonitor()</strong> shows how to use lifecycle hooks:</p>
<ul>
<li><strong>onMounted()</strong> - Auto-connect and monitoring initialization</li>
<li><strong>onUnmounted()</strong> - Cleaning up intervals and disconnect</li>
<li>Each composable instance has its own lifecycle hooks</li>
<li>Automatic resource management (timers, connections)</li>
<li>Preventing memory leaks through cleanup in onUnmounted</li>
</ul>
<div class="code-example">
<code>
function useConnectionMonitor(url) {
onMounted(() => {
// Setup: auto-connect, start monitoring
})
onUnmounted(() => {
// Cleanup: clear timers, disconnect
})
return { isConnected, connect, disconnect }
}
</code>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.connection-lab {
background: linear-gradient(135deg, #0a0e27 0%, #1a1e3f 100%);
min-height: 100vh;
padding: 2rem;
color: #ffffff;
font-family: 'Courier New', monospace;
}
.header {
text-align: center;
margin-bottom: 2rem;
padding-bottom: 1rem;
border-bottom: 2px solid #00ff88;
}
.header h1 {
font-size: 2.5rem;
color: #00ff88;
text-shadow: 0 0 20px rgba(0, 255, 136, 0.5);
margin: 0;
}
.subtitle {
color: #00b4d8;
font-size: 1.2rem;
margin-top: 0.5rem;
}
.connections-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
gap: 1.5rem;
margin-bottom: 2rem;
}
.connection-card {
background: rgba(255, 0, 85, 0.1);
border: 2px solid #ff0055;
border-radius: 10px;
padding: 1.5rem;
transition: all 0.3s ease;
}
.connection-card.connected {
background: rgba(0, 255, 136, 0.1);
border-color: #00ff88;
}
.connection-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
}
.connection-header h3 {
color: #00ff88;
margin: 0;
font-size: 1.3rem;
}
.status-indicator {
padding: 0.5rem 1rem;
border-radius: 20px;
background: rgba(255, 0, 85, 0.3);
color: #ff0055;
font-weight: bold;
font-size: 0.9rem;
}
.status-indicator.active {
background: rgba(0, 255, 136, 0.3);
color: #00ff88;
animation: pulse 2s infinite;
}
.connection-stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
margin-bottom: 1rem;
}
.stat-item {
background: rgba(0, 0, 0, 0.3);
padding: 1rem;
border-radius: 5px;
text-align: center;
}
.stat-label {
display: block;
color: #00b4d8;
font-size: 0.8rem;
margin-bottom: 0.5rem;
}
.stat-value {
display: block;
color: #ffb400;
font-size: 1.5rem;
font-weight: bold;
}
.stat-value.good {
color: #00ff88;
}
.connection-times {
background: rgba(0, 0, 0, 0.3);
padding: 1rem;
border-radius: 5px;
margin-bottom: 1rem;
min-height: 60px;
}
.time-info {
color: #ffffff;
font-size: 0.9rem;
margin: 0.25rem 0;
}
.connection-controls {
display: flex;
gap: 0.5rem;
margin-bottom: 1rem;
}
.messages-log {
background: rgba(0, 0, 0, 0.5);
border-radius: 5px;
padding: 1rem;
max-height: 200px;
overflow-y: auto;
}
.log-message {
display: flex;
gap: 1rem;
padding: 0.5rem;
margin: 0.25rem 0;
border-left: 3px solid;
border-radius: 3px;
font-size: 0.85rem;
}
.msg-success {
border-color: #00ff88;
background: rgba(0, 255, 136, 0.1);
}
.msg-warning {
border-color: #ffb400;
background: rgba(255, 180, 0, 0.1);
}
.msg-error {
border-color: #ff0055;
background: rgba(255, 0, 85, 0.1);
}
.msg-info {
border-color: #00b4d8;
background: rgba(0, 180, 216, 0.1);
}
.msg-time {
color: #00b4d8;
min-width: 80px;
font-size: 0.75rem;
}
.msg-text {
color: #ffffff;
flex: 1;
}
.btn {
flex: 1;
padding: 0.75rem;
border: none;
border-radius: 5px;
font-weight: bold;
cursor: pointer;
font-family: 'Courier New', monospace;
transition: all 0.3s ease;
font-size: 0.9rem;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-success {
background: #00ff88;
color: #0a0e27;
}
.btn-danger {
background: #ff0055;
color: #ffffff;
}
.btn-warning {
background: #ffb400;
color: #0a0e27;
}
.btn:not(:disabled):hover {
transform: scale(1.05);
box-shadow: 0 5px 15px rgba(0, 255, 136, 0.3);
}
.info-panel {
background: rgba(0, 180, 216, 0.05);
border: 2px solid #00b4d8;
border-radius: 10px;
padding: 2rem;
}
.info-panel h3 {
color: #00ff88;
margin-top: 0;
margin-bottom: 1.5rem;
}
.info-content ul {
list-style: none;
padding: 0;
}
.info-content li {
padding: 0.5rem 0;
color: #ffffff;
line-height: 1.6;
}
.code-example {
background: rgba(0, 0, 0, 0.5);
border-left: 4px solid #00ff88;
border-radius: 5px;
padding: 1rem;
margin-top: 1rem;
}
.code-example code {
color: #00ff88;
font-size: 0.9rem;
white-space: pre;
display: block;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.6; }
}
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the VueUse library offer?
2. What is useLocalStorage from VueUse used for?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create a responsive component with computed properties isMobile, isTablet, isDesktop.
- Vertical ordering
Arrange the steps for installing and using VueUse:
- Click in order
Arrange the import of a composable from VueUse:
- Code editor
Use useDark and useToggle to create a dark mode toggle with the appropriate CSS class.
- Horizontal ordering
Arrange the destructuring of useWindowSize: