溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

好用的VueUse函數有哪些

發布時間:2021-08-17 09:19:05 來源:億速云 閱讀:198 作者:小新 欄目:編程語言
# 好用的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 - 支持狀態重置

useFetch

const { data, error, abort } = useFetch('https://api.example.com', {
  immediate: false,
  refetch: true
})

參數配置

參數 類型 默認值 說明
immediate boolean true 是否立即執行請求
timeout number 0 請求超時時間(ms)

useStorage

// 自動同步到localStorage
const state = useStorage('my-store', {
  token: '',
  darkMode: false
})

存儲類型: - localStorage: 持久化存儲 - sessionStorage: 會話級存儲 - 自定義存儲適配器

瀏覽器API相關

useClipboard

const { copy, copied } = useClipboard()

copy('要復制的文本') 
// copied.value 會在2秒后自動重置

高級用法

// 讀取剪貼板內容
const { text, read } = useClipboard()
read()

useTitle

// 動態修改頁面標題
const title = useTitle('初始標題')
title.value = '新標題'

特性: - 支持響應式更新 - 離開頁面時自動恢復原標題

useGeolocation

const { coords, error, resume, pause } = useGeolocation()

返回數據

interface Coords {
  accuracy: number
  latitude: number
  longitude: number
  altitude: number | null
  // ...其他GPS數據
}

UI交互增強

useMouse

const { x, y, sourceType } = useMouse()

跟蹤模式

// 相對元素位置
const { elementX, elementY } = useMouse({ target: ref })

useElementSize

<template>
  <div ref="el"></div>
</template>

<script setup>
const el = ref(null)
const { width, height } = useElementSize(el)
</script>

邊界處理: - 自動處理元素未掛載情況 - 支持ResizeObserver降級方案

useDraggable

const el = ref(null)
const { x, y, style } = useDraggable(el, {
  initialValue: { x: 40, y: 40 }
})

配置選項

interface Options {
  exact?: boolean       // 精確拖動模式
  preventDefault?: boolean
  stopPropagation?: boolean
  // ...共15+配置項
}

動畫與過渡

useTransition

const output = useTransition(sourceNumber, {
  duration: 1000,
  transition: [0.75, 0, 0.25, 1] // 貝塞爾曲線
})

動畫類型: - 線性動畫 - 彈簧動畫 - 自定義緩動函數

useInterval

const { counter, pause, resume } = useInterval(1000, {
  controls: true,
  immediate: false
})

精準控制

// 動態調整間隔
const interval = ref(1000)
useInterval(interval)

狀態管理

useCounter

const { count, inc, dec, set } = useCounter(0, {
  min: 0,
  max: 10
})

方法列表

方法 參數 說明
inc() delta=1 增加指定步長
dec() delta=1 減少指定步長
set() value 直接設置新值

useToggle

const [value, toggle] = useToggle(false)
// 切換布爾值
toggle()
// 指定值
toggle(true)

多值切換

const [state, toggle] = useToggle(['red', 'green', 'blue'])

高級組合

useDebounceFn

const debouncedFn = useDebounceFn(() => {
  // 業務邏輯
}, 500)

input.addEventListener('input', debouncedFn)

特性比較

類型 觸發時機 典型場景
debounce 停止操作后延遲執行 搜索框輸入
throttle 固定間隔執行一次 滾動事件處理

useThrottleFn

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集成方案等擴展內容)

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女