# 好用的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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。