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

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

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

相关推荐
用户23678298016810 小时前
从零实现 GIF 制作工具:LZW 压缩与 Median Cut 色彩量化
前端·javascript
棉猴10 小时前
Python海龟绘图之绘制文本
javascript·python·html·write·turtle·海龟绘图·输出文本
Highcharts.js11 小时前
线形比赛积分增长或竞赛图|Highcharts企业图表代码示列
开发语言·前端·javascript·折线图·highcharts·竞赛图
让学习成为一种生活方式11 小时前
大肠杆菌合成扑热息痛--对乙酰氨基酚--文献精读227
开发语言·前端·javascript
多秋浮沉度华年11 小时前
electron 初始使用记录
javascript·arcgis·electron
竹林81812 小时前
用 wagmi v2 + WebSocket 硬磕 NFT 上架失败:一个前端开发者踩过的实时状态同步坑
javascript·next.js
豹哥学前端12 小时前
告别割裂式学习:待办清单项目,一次性掌握数组、本地存储与事件委托
前端·javascript
JYeontu12 小时前
照片墙太死板?做一个会随风摇摆的绳串图片交互效果
前端·javascript·css
Yue栎廷12 小时前
邪修:Markdown加粗语法**本土化改造
前端·javascript·人工智能
小歪 | 前端12 小时前
VUE_运行Vue项目Network: unavailable问题解决
前端·javascript·vue.js