我们项目中如何运用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。

工程化集成方案

现代构建工具链中推荐配置:

bash 复制代码
npm install @vueuse/core @vueuse/components

TypeScript项目需在tsconfig.json中配置类型提示:

json 复制代码
{
  "compilerOptions": {
    "types": ["@vueuse/core"]
  }
}

Volar插件提供完整的代码补全支持,配合unplugin-auto-import实现自动导入:

javascript 复制代码
// 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进行单元测试:

javascript 复制代码
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

极致简化的代码,使用起来是非常的舒适的,比如说,我们开发过程中需要用到一些本地存储,那么可以使用它,

javascript 复制代码
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进行操作,

javascript 复制代码
<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>

我们就不需要自己去封装一个复制相关的代码了。

这些函数都需要多去使用才能够熟练,或者需要用的时候去官网找到对应的方法,能够加快我们开发的脚步。

相关推荐
EndingCoder7 小时前
接口基础:定义对象形状
linux·运维·前端·javascript·typescript
WebGISer_白茶乌龙桃7 小时前
Vue3 + Mapbox 加载 SHP 转换的矢量瓦片 (Vector Tiles)
javascript·vue.js·arcgis·webgl
Aliex_git8 小时前
性能优化 - Vue 日常实践优化
前端·javascript·vue.js·笔记·学习·性能优化
xiaoxue..8 小时前
把大模型装进自己电脑:Ollama 本地部署大模型完全指南
javascript·面试·node.js·大模型·ollama
林恒smileZAZ8 小时前
Electron 的西天取经
前端·javascript·electron
Miketutu8 小时前
Flutter - 布局
开发语言·javascript·ecmascript
满栀5858 小时前
基于 jQuery 实现商品列表增删改查与数据统计
前端·javascript·jquery
Mr -老鬼8 小时前
Electron 与 Tauri 全方位对比指南(2026版)
前端·javascript·rust·electron·nodejs·tauri
幻云20108 小时前
Next.js 之道:从全栈思维到架构实战
开发语言·javascript·架构
king王一帅12 小时前
Incremark Solid 版本上线:Vue/React/Svelte/Solid 四大框架,统一体验
前端·javascript·人工智能