VueUse基于Vue Composition API的工具库,提供200+开箱即用的函数,覆盖状态管理、浏览器API、动画等高频场景。
三大核心优势:
- 即插即用:无需从零实现防抖、本地存储等功能
- 性能优化:自动清理事件监听和定时器,避免内存泄漏
- 跨版本兼容:同时支持Vue2和Vue3,迁移成本降低80%
核心功能解密
1. 状态管理「智能管家」
传统方式需要手动操作localStorage:
// 旧方案
let data = JSON.parse(localStorage.getItem('key')) || {}
data.value = 'new'
localStorage.setItem('key', JSON.stringify(data))
VueUse一键搞定:
import { useLocalStorage } from '@vueuse/core'
const userPrefs = useLocalStorage('settings', { theme: 'light' })
userPrefs.value.theme = 'dark' // 自动同步到本地存储
2. 浏览器API「降维打击」
监听鼠标位置只需3行代码:
const { x, y } = useMouse()
watch([x, y], ([newX, newY]) => {
console.log(`光标位置:${newX}, ${newY}`)
})
3. 动画交互「黑科技」
实现元素拖拽无需第三方库:
<template>
<div ref="dragElement" style="width:100px;height:100px;background:red"></div>
</template>
<script setup>
import { useDraggable } from '@vueuse/core'
const dragElement = ref(null)
useDraggable(dragElement) // 瞬间获得拖拽能力
</script>
4. 网络请求「极简封装」
const { data, error } = useFetch('/api/user')
const { execute: refresh } = useFetch('/api/update', {
immediate: false // 手动触发请求
})
实战场景解析
场景1:表单防抖优化
传统方案需要手动封装:
let timer = null
const handleSearch = (query) => {
clearTimeout(timer)
timer = setTimeout(() => {
// 搜索逻辑
}, 300)
}
VueUse方案:
const debouncedSearch = useDebounceFn((query) => {
// 搜索逻辑
}, 300)
场景2:跨组件状态共享
// store.js
export const useGlobalStore = createGlobalState(() => {
const count = ref(0)
const increment = () => count.value++
return { count, increment }
})
// 任意组件
const { count, increment } = useGlobalStore()
场景3:响应式DOM操作
const element = ref(null)
const { width, height } = useElementSize(element)
watch([width, height], () => {
console.log('元素尺寸变化:', width.value, height.value)
})
性能优化指南
- 按需引入:避免全量导入
import { useMouse } from '@vueuse/core' //
import VueUse from '@vueuse/core' //
- 内存管理:自动清理的三种场景:
- 组件卸载时自动移除事件监听
- 定时器自动销毁
- 网络请求自动abort
- 移动端适配:使用useTouchGesture处理手势交互,替代第三方手势库
开发建议:结合Vue DevTools的Timeline面板,监控hook执行效率。
VueUse个人感觉最牛逼的是它的源码,去看看源码里面用到的各种技巧,自己试着去复刻一遍,对技术的提升也是肉眼可见的。