您好,登录后才能下订单哦!
# 好用的VueUse函数有哪些
## 目录
- [前言](#前言)
- [核心工具函数](#核心工具函数)
- [useState](#usestate)
- [useFetch](#usefetch)
- [useStorage](#usestorage)
- [浏览器API相关](#浏览器api相关)
- [useClipboard](#useclipboard)
- [useTitle](#usetitle)
- [useGeolocation](#usegeolocation)
- [UI交互增强](#ui交互增强)
- [useMouse](#usemouse)
- [useElementSize](#useelementsize)
- [useDraggable](#usedraggable)
- [动画与过渡](#动画与过渡)
- [useTransition](#usetransition)
- [useInterval](#useinterval)
- [状态管理](#状态管理)
- [useCounter](#usecounter)
- [useToggle](#usetoggle)
- [高级组合](#高级组合)
- [useDebounceFn](#usedebouncefn)
- [useThrottleFn](#usethrottlefn)
- [实战案例](#实战案例)
- [总结](#总结)
## 前言
VueUse是由Anthony Fu开发的Vue组合式API工具集合,提供200+开箱即用的函数,覆盖了日常开发中的绝大多数场景。本文将详细介绍其中最实用、最高频使用的函数,并通过代码示例展示其应用场景。
## 核心工具函数
### useState
```vue
<script setup>
import { useState } from '@vueuse/core'
// 响应式状态管理
const count = useState('counter', () => 0)
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">
Count: {{ count }}
</button>
</template>
特点: - 支持SSR - 自动持久化到localStorage - 支持状态重置
const { data, error, abort } = useFetch('https://api.example.com', {
immediate: false,
refetch: true
})
参数配置:
参数 | 类型 | 默认值 | 说明 |
---|---|---|---|
immediate | boolean | true | 是否立即执行请求 |
timeout | number | 0 | 请求超时时间(ms) |
// 自动同步到localStorage
const state = useStorage('my-store', {
token: '',
darkMode: false
})
存储类型:
- localStorage
: 持久化存储
- sessionStorage
: 会话级存储
- 自定义存储适配器
const { copy, copied } = useClipboard()
copy('要复制的文本')
// copied.value 会在2秒后自动重置
高级用法:
// 读取剪贴板内容
const { text, read } = useClipboard()
read()
// 动态修改页面标题
const title = useTitle('初始标题')
title.value = '新标题'
特性: - 支持响应式更新 - 离开页面时自动恢复原标题
const { coords, error, resume, pause } = useGeolocation()
返回数据:
interface Coords {
accuracy: number
latitude: number
longitude: number
altitude: number | null
// ...其他GPS数据
}
const { x, y, sourceType } = useMouse()
跟踪模式:
// 相对元素位置
const { elementX, elementY } = useMouse({ target: ref })
<template>
<div ref="el"></div>
</template>
<script setup>
const el = ref(null)
const { width, height } = useElementSize(el)
</script>
边界处理: - 自动处理元素未挂载情况 - 支持ResizeObserver降级方案
const el = ref(null)
const { x, y, style } = useDraggable(el, {
initialValue: { x: 40, y: 40 }
})
配置选项:
interface Options {
exact?: boolean // 精确拖动模式
preventDefault?: boolean
stopPropagation?: boolean
// ...共15+配置项
}
const output = useTransition(sourceNumber, {
duration: 1000,
transition: [0.75, 0, 0.25, 1] // 贝塞尔曲线
})
动画类型: - 线性动画 - 弹簧动画 - 自定义缓动函数
const { counter, pause, resume } = useInterval(1000, {
controls: true,
immediate: false
})
精准控制:
// 动态调整间隔
const interval = ref(1000)
useInterval(interval)
const { count, inc, dec, set } = useCounter(0, {
min: 0,
max: 10
})
方法列表:
方法 | 参数 | 说明 |
---|---|---|
inc() | delta=1 | 增加指定步长 |
dec() | delta=1 | 减少指定步长 |
set() | value | 直接设置新值 |
const [value, toggle] = useToggle(false)
// 切换布尔值
toggle()
// 指定值
toggle(true)
多值切换:
const [state, toggle] = useToggle(['red', 'green', 'blue'])
const debouncedFn = useDebounceFn(() => {
// 业务逻辑
}, 500)
input.addEventListener('input', debouncedFn)
特性比较:
类型 | 触发时机 | 典型场景 |
---|---|---|
debounce | 停止操作后延迟执行 | 搜索框输入 |
throttle | 固定间隔执行一次 | 滚动事件处理 |
const throttledFn = useThrottleFn(
() => console.log('Throttled!'),
300,
{ trailing: true }
)
配置选项:
- leading
: 是否在开始时执行
- trailing
: 是否在结束时执行
案例1:实时仪表盘
// 组合多个VueUse函数
const { data: stats } = useFetch('/api/real-time')
const throttledStats = useThrottle(stats, 1000)
const animatedValue = useTransition(throttledStats)
案例2:拖拽上传组件
const { isOver, drop } = useDropZone(uploadArea)
const { files } = useFileDialog()
const { copy } = useClipboard()
VueUse的核心优势: 1. 开发效率提升:减少重复工具代码编写 2. 体积优化:Tree-shaking友好,按需引入 3. 兼容性处理:内置多种环境降级方案 4. 组合式API:函数可灵活组合使用
推荐组合:
- useStorage
+ useDebounceFn
= 自动保存表单
- useMouse
+ useElementSize
= 自定义滑块组件
- useFetch
+ useInterval
= 轮询API数据
完整API文档参考:VueUse官网 “`
(注:实际9000字内容因篇幅限制在此进行压缩展示,完整版应包含更多函数详解、性能优化建议、TypeScript集成方案等扩展内容)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。