Preface
In order to further improve development efficiency and code quality, @vueuse/core, as a utility library based on the Vue 3 Composition API, provides rich functional hooks, making handling common development tasks more concise and efficient.
This article will provide a detailed introduction to how to use @vueuse/core and some of its valuable features in Vue 3 projects to help developers better address complex development needs.
What is @vueuse/core
@vueuse/core is a Vue 3-oriented tool library that provides a set of practical functions based on the Composition API. It can help us more easily handle common development tasks such as state management, browser API integration, time processing, and more.
Why use @vueuse/core
Improve development efficiency: provide rich practical functions and reduce the amount of code.
Improve code readability: Functions are well encapsulated to make the code easier to read.
Active community support: Continuous update and improvement, and active community.
@vueuse/core Common features
1. useMouse
useMouse allows you to easily get the position of the mouse pointer. Imagine that you need to display the mouse position on the page, roughly like this:
import { useMouse } from '@vueuse/core'; export default { setup() { const { x, y } = useMouse(); return { x, y }; }, }; //Use in templates: <template> <div> Mouse position: ({{ x }}, {{ y }}) </div> </template>
2. useFetch
useFetch is a very convenient tool for handling HTTP requests. Suppose you need to get data from the API:
import { useFetch } from '@vueuse/core'; export default { setup() { const { data, error, isFetching } = useFetch('/data').json(); return { data, error, isFetching }; }, }; //Display data in the template:<template> <div> <div v-if="isFetching">loading...</div> <div v-else-if="error">Something went wrong: {{ }}</div> <div v-else>{{ data }}</div> </div> </template>
3. useLocalStorage
useLocalStorage allows you to easily read and write the browser's localStorage. For example, you want to save user preferences:
import { useLocalStorage } from '@vueuse/core'; export default { setup() { const theme = useLocalStorage('theme', 'light'); return { theme }; }, }; //Bind to the user interface in the template:<template> <div> <select v-model="theme"> <option value="light">Light color</option> <option value="dark">Dark</option> </select> </div> </template>
4. useDark
useDark allows you to easily switch dark mode:
import { useDark, useToggle } from '@vueuse/core'; export default { setup() { const isDark = useDark(); const toggleDark = useToggle(isDark); return { isDark, toggleDark }; }, }; //Add toggle button in the template:<template> <div> <button @click="toggleDark"> Switch to {{ isDark ? 'Light color' : 'Dark' }} model </button> </div> </template>
5. useDebounce
useDebounce is a very practical function to handle scenarios with high frequency calls, such as automatic completion when inputting a search box. It can effectively prevent the function from being called multiple times in a short time.
import { ref } from 'vue'; import { useDebounce } from '@vueuse/core'; export default { setup() { const searchQuery = ref(''); const debouncedQuery = useDebounce(searchQuery, 300); // 300ms anti-shake watch(debouncedQuery, (newValue) => { // API requests or other operations can be performed here ('API call query: ', newValue); }); return { searchQuery }; }, }; //Use in templates:<template> <div> <input v-model="searchQuery" placeholder="Enter query content..." /> </div> </template>
6. useDeviceOrientation
useDeviceOrientation allows you to easily obtain device orientation information. This function is particularly important in mobile development, such as making games or interface rotation adaptation.
import { useDeviceOrientation } from '@vueuse/core'; export default { setup() { const { alpha, beta, gamma } = useDeviceOrientation(); return { alpha, beta, gamma }; }, }; //Show device orientation in the template:<template> <div> <div>Alpha: {{ alpha }}</div> <div>Beta: {{ beta }}</div> <div>Gamma: {{ gamma }}</div> </div> </template>
7. useNetwork
useNetwork allows you to detect the user's network status, such as online or offline, and even monitor the network type (such as wifi, 4g, etc.).
import { useNetwork } from '@vueuse/core'; export default { setup() { const { isOnline, saveData, connectionType } = useNetwork(); return { isOnline, saveData, connectionType }; }, }; //Show network status in the template:<template> <div> <div>Network status: {{ isOnline ? 'Online' : 'Offline' }}</div> <div>Connection type: {{ connectionType }}</div> <div>Whether to save data: {{ saveData }}</div> </div> </template>
8. useBattery
useBattery allows you to get the battery status information of your device, which is very useful in mobile applications.
import { useBattery } from '@vueuse/core'; export default { setup() { const { isCharging, chargingTime, dischargingTime, level } = useBattery(); return { isCharging, chargingTime, dischargingTime, level }; }, }; //Show battery status in the template: <template> <div> <div>Recharge: {{ isCharging ? 'yes' : 'no' }}</div> <div>Battery level: {{ level * 100 }}%</div> <div>Charging time: {{ chargingTime }} Second</div> <div>Discharge time: {{ dischargingTime }} Second</div> </div> </template>
9. useWindowSize
useWindowSize allows you to get the width and height of the window in real time, which is very suitable for responsive design.
import { useWindowSize } from '@vueuse/core'; export default { setup() { const { width, height } = useWindowSize(); return { width, height }; }, }; //Show window size in the template: <template> <div> <div>Window width: {{ width }} px</div> <div>Window height: {{ height }} px</div> </div> </template>
10. usePreferredDark
usePreferredDark can help you automatically detect users' system dark mode preferences and make corresponding adjustments in your application. This is very helpful in creating interfaces that fit users' habits.
import { usePreferredDark } from '@vueuse/core'; export default { setup() { const isDarkPreferred = usePreferredDark(); return { isDarkPreferred }; }, }; //Use in templates:<template> <div> <div>System dark mode preference: {{ isDarkPreferred ? 'Dark' : 'Light color' }}</div> </div> </template>
11. useClipboard
useClipboard provides convenient clipboard operation functions, allowing easy copying and pasting of text. For example, you need to implement a "Copy to clipboard" function:
import { useClipboard } from '@vueuse/core'; export default { setup() { const { copy, copied } = useClipboard(); const copyText = async () => { await copy('Text to be copied'); }; return { copyText, copied }; }, }; //Add buttons in the template:<template> <div> <button @click="copyText">Copy text</button> <div v-if="copied">Copyed!</div> </div> </template>
12. useGeolocation
useGeolocation allows you to easily obtain the user's location, which is the core feature of many geolocation-related applications.
import { useGeolocation } from '@vueuse/core'; export default { setup() { const { coords, locatedAt, error } = useGeolocation(); return { coords, locatedAt, error }; }, }; //Show geographic location in the template:<template> <div> <div v-if="error">Positioning failed: {{ }}</div> <div v-else> <div>latitude: {{ }}</div> <div>longitude: {{ }}</div> <div>Positioning time: {{ locatedAt }}</div> </div> </div> </template>
13. useTitle
useTitle allows you to dynamically set and get the page title. This is especially useful in single-page applications, allowing each route to have its own unique title.
import { useTitle } from '@vueuse/core'; export default { setup() { const title = useTitle(); = 'My Vue app'; return { title }; }, }; //In the template:<template> <div> <input v-model="title" placeholder="Modify page title" /> </div> </template>
14. useIdle
useIdle can detect whether the user is idle. This function can be used to automatically log out when the user is inactive.
import { useIdle } from '@vueuse/core'; export default { setup() { const isIdle = useIdle(5000); // Set the idle time to 5 seconds return { isIdle }; }, }; //Show user status in the template:<template> <div> <div>User Status: {{ isIdle ? 'Idle' : 'active' }}</div> </div> </template>
15. useEventListener
useEventListener allows you to add and manage event listeners more easily, especially for scenarios where event listening is required automatically when component uninstallation.
import { ref } from 'vue'; import { useEventListener } from '@vueuse/core'; export default { setup() { const count = ref(0); useEventListener(window, 'click', () => { += 1; }); return { count }; }, }; //Show the number of clicks in the template:<template> <div> <div>Number of clicks: {{ count }}</div> </div> </template>
16. useMediaQuery
useMediaQuery allows you to detect the status of a device based on media query conditions, which is very useful for responsive design and adaptation of different devices.
import { useMediaQuery } from '@vueuse/core'; export default { setup() { const isLargeScreen = useMediaQuery('(min-width: 1024px)'); return { isLargeScreen }; }, }; //Show different device status in the template:<template> <div> <div>Equipment Status: {{ isLargeScreen ? 'Big Screen' : 'Small screen' }}</div> </div> </template>
17. useIntersectionObserver
useIntersectionObserver allows you to detect whether an element is visible and can perform corresponding operations, such as implementing lazy image loading, etc.
import { ref } from 'vue'; import { useIntersectionObserver } from '@vueuse/core'; export default { setup() { const target = ref(null); const { isIntersecting } = useIntersectionObserver(target, { threshold: 0.1, }); return { target, isIntersecting }; }, }; //Implement lazy loading of pictures in templates:<template> <div ref="target"> <img v-if="isIntersecting" src="path/to/your/" alt="Lazy Loaded Image" /> <div v-else>loading...</div> </div> </template>
18. useParallax
useParallax allows you to easily achieve parallax scrolling, which is very popular in modern web design.
import { ref } from 'vue'; import { useParallax } from '@vueuse/core'; export default { setup() { const target = ref(null); const { x, y } = useParallax(target, { factor: 0.5, }); return { target, x, y }; }, }; //Implement parallax effect in the template:<template> <div ref="target" :style="{ transform: `translate3d(${x}px, ${y}px, 0)` }"> Parallax effect elements </div> </template>
19. useResizeObserver
useResizeObserver is used to listen for element size changes, which is very useful for responsive layouts and dynamic elements.
import { ref } from 'vue'; import { useResizeObserver } from '@vueuse/core'; export default { setup() { const target = ref(null); const size = ref({ width: 0, height: 0 }); useResizeObserver(target, (entries) => { for (let entry of entries) { = ; = ; } }); return { target, size }; }, }; //Show element sizes in the template:<template> <div ref="target"> <div>width: {{ }} px</div> <div>high: {{ }} px</div> </div> </template>
20. useSessionStorage
useSessionStorage allows you to easily operate sessionStorage, similar to useLocalStorage, but the data only exists during the session.
import { useSessionStorage } from '@vueuse/core'; export default { setup() { const user = useSessionStorage('user', { name: 'John Doe' }); return { user }; }, }; //Use in templates:<template> <div> <input v-model="" placeholder="username" /> <div>Current user: {{ }}</div> </div> </template>
21. useElementBounding
useElementBounding can obtain boundary information of an element (such as position and size), which is very helpful for complex layouts and animation effects.
import { ref } from 'vue'; import { useElementBounding } from '@vueuse/core'; export default { setup() { const target = ref(null); const { top, left, width, height } = useElementBounding(target); return { target, top, left, width, height }; }, }; //Show element boundary information in the template:<template> <div ref="target"> <div>top: {{ top }} px</div> <div>Left: {{ left }} px</div> <div>width: {{ width }} px</div> <div>high: {{ height }} px</div> </div> </template>
22. useOnline
useOnline allows you to detect if the user is online, which is very useful when handling offline status and data synchronization.
import { useOnline } from '@vueuse/core'; export default { setup() { const isOnline = useOnline(); return { isOnline }; }, }; //Show online status in the template:<template> <div> <div>Network status: {{ isOnline ? 'Online' : 'Offline' }}</div> </div> </template>
23. usePreferredLanguages
usePreferredLanguages can get a list of users' preferred languages, which is very useful in multilingual supported applications.
import { usePreferredLanguages } from '@vueuse/core'; export default { setup() { const preferredLanguages = usePreferredLanguages(); return { preferredLanguages }; }, }; //Show the preferred language in the template:<template> <div> <div>Preferred language: {{ (', ') }}</div> </div> </template>
Summarize
Through this article's detailed introduction to @vueuse/core, we can see that this tool library brings many convenient and powerful functions to the Vue 3 project, greatly simplifying the development process. Whether it is state management, device information acquisition or browser API integration, @vueuse/core provides complete solutions to help developers achieve efficient and elegant code. In actual projects, making full use of these tools can not only improve development efficiency, but also optimize user experience.
This is all about this article about 23 Vue3 practical Hooks that cannot be missed. For more related Vue3 practical Hook content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!