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

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

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

相关推荐
MoonBit月兔1 天前
海外开发者实践分享:用 MoonBit 开发 SQLC 插件(其二)
开发语言·javascript·数据库·redis·mysql·moonbit
前端李易安1 天前
ERROR in ./node_modules/vue-router/dist/vue-router.mjs 被报错折磨半天?真相竟是……
前端·javascript·vue.js
monkey_slh1 天前
JS逆向实战——最新某东cfe滑块
开发语言·前端·javascript
2503_928411561 天前
12.17 vue递归组件
前端·javascript·vue.js
如果你好1 天前
🔥 手撕call/apply/bind:从ES6用法到手写实现,吃透this指向核心
前端·javascript
@大迁世界1 天前
React 以惨痛的方式重新吸取了 25 年前 RCE 的一个教训
前端·javascript·react.js·前端框架·ecmascript
晴殇i1 天前
【拿来就用】Uniapp路由守卫终极方案:1个文件搞定全站权限控制,老板看了都点赞!
前端·javascript·面试
遇见很ok1 天前
Web Worker
前端·javascript·vue.js
elangyipi1231 天前
JavaScript 高级错误处理与 Chrome 调试艺术
开发语言·javascript·chrome
前端不太难1 天前
RN Navigation vs Vue Router:从架构底层到工程实践的深度对比
javascript·vue.js·架构