我们项目中如何运用vueuse
背景
最近项目中遇见了别人使用了vueuse的存储方法,感觉这个组合式函数集合还是比较多的地方可以用到的,而我之前没有怎么使用它,现在做一个简单的介绍。GITHUB网址和官网:https://vueuse.org/ ; https://github.com/vueuse/vueuse
核心功能模块化
VueUse 提供 200+ 组合式函数,按功能领域划分为九大类别。根据项目需求选择对应模块:
- 状态管理:
useStorage实现本地存储同步,useSessionStorage处理会话级数据 - 元素交互:
useMouse追踪光标位置,useIntersectionObserver优化懒加载 - 网络请求:
useFetch封装HTTP请求,useWebSocket建立实时连接 - 动画效果:
useTransition实现数值过渡,useRafFn优化帧动画
性能优化实践
组合式函数自带智能优化机制,典型场景包括:
useDebounceFn延迟执行高频操作,适用于搜索框输入useThrottleFn限制函数调用频率,处理滚动事件时特别有效useIdle检测用户闲置状态,可暂停非关键后台任务
重要数据流使用computedAsync处理异步计算,避免阻塞UI渲染。对于复杂状态逻辑,createGlobalState支持跨组件共享状态而无需引入Pinia。
工程化集成方案
现代构建工具链中推荐配置:
npm install @vueuse/core @vueuse/components
TypeScript项目需在tsconfig.json中配置类型提示:
{"compilerOptions": {"types": ["@vueuse/core"]}
}
Volar插件提供完整的代码补全支持,配合unplugin-auto-import实现自动导入:
// vite.config.js
import AutoImport from 'unplugin-auto-import/vite'export default {plugins: [AutoImport({imports: ['@vueuse/core']})]
}
移动端适配技巧
触摸交互相关函数提升移动体验:
useSwipe检测滑动方向,实现轮播图控制useBattery获取设备电量,优化资源密集型操作useDeviceOrientation响应屏幕旋转,调整布局
传感器数据通过useGeolocation获取用户位置,useDevicePixelRatio处理高清屏显示问题。usePreferredDark结合CSS变量实现暗色模式切换。
测试策略
组合式函数支持独立测试,使用renderHook进行单元测试:
import { useCounter } from '@vueuse/core'
import { renderHook } from '@testing-library/vue'test('should increment counter', () => {const { result } = renderHook(() => useCounter())expect(result.current.count.value).toBe(0)result.current.inc()expect(result.current.count.value).toBe(1)
})
E2E测试中可利用useTitle验证页面标题变更,useFavicon检测网站图标更新。useClipboard需要特殊处理浏览器API mock。
官网有几个部分组成
State
Elments
Browser
Sensors
Network
Animation
Component
Watch
Reactivity
Array
Time
Utilities
极致简化的代码,使用起来是非常的舒适的,比如说,我们开发过程中需要用到一些本地存储,那么可以使用它,
import { useStorage } from '@vueuse/core'// bind object
const state = useStorage('my-store', { hello: 'hi', greeting: 'Hello' })// bind boolean
const flag = useStorage('my-flag', true) // returns Ref<boolean>// bind number
const count = useStorage('my-count', 0) // returns Ref<number>// bind string with SessionStorage
const id = useStorage('my-id', 'some-string-id', sessionStorage) // returns Ref<string>// delete data from storage
state.value = null
这样我们就可以轻松存值了。
如果我们需要操作复制文字的功能,我们可以直接用 useClipboard进行操作,
<script setup lang="ts">
import { useClipboard } from '@vueuse/core'const source = ref('Hello')
const { text, copy, copied, isSupported } = useClipboard({ source })
</script><template><div v-if="isSupported"><button @click="copy(source)"><!-- by default, `copied` will be reset in 1.5s --><span v-if="!copied">Copy</span><span v-else>Copied!</span></button><p>Current copied: <code>{{ text || 'none' }}</code></p></div><p v-else>Your browser does not support Clipboard API</p>
</template>
我们就不需要自己去封装一个复制相关的代码了。
这些函数都需要多去使用才能够熟练,或者需要用的时候去官网找到对应的方法,能够加快我们开发的脚步。
