Vue系列——第 24 篇:VueUse——组合式工具集的百宝箱

本篇定位:VueUse 是 Vue 3 生态中最强大的组合式工具库,它提供了近 200 个开箱即用的组合式函数,涵盖 DOM 操作、浏览器 API、状态管理、动画、网络请求等各个领域。本篇将系统讲解 VueUse 的安装使用、核心工具函数、自定义组合式函数开发以及在实际项目中的应用。读完本篇,你将能够熟练运用 VueUse 大幅提升开发效率。


一、VueUse 概述

1.1 什么是 VueUse?

VueUse 是由 Vue 核心团队成员 Anthony Fu 创建和维护的组合式 API 工具集。它基于 Vue 3 的组合式 API,提供了大量高质量的、可复用的组合式函数。

VueUse 的核心理念:

复制代码
"组合式 API 让逻辑复用成为可能,VueUse 让逻辑复用变得简单"

VueUse 的代码质量:VueUse 的每个函数都经过精心设计,代码质量极高,可以放心在生产环境中使用。社区贡献活跃,持续更新。

1.2 为什么需要 VueUse?

问题 VueUse 的解决方案
需要监听鼠标位置 useMouse()
需要持久化状态 useLocalStorage()
需要防抖/节流 useDebounceFn() / useThrottleFn()
需要监听元素可见性 useIntersectionObserver()
需要获取网络状态 useOnline()
需要管理定时器 useInterval() / useTimeout()
需要处理剪贴板 useClipboard()
需要响应式断点 useBreakpoints()

VueUse 的核心优势:

  • 开箱即用:近 200 个工具函数,覆盖日常开发 80% 的需求
  • 类型安全:完整的 TypeScript 支持
  • 轻量级:按需引入,Tree Shaking 友好
  • 响应式:所有函数都基于 Vue 响应式系统
  • SSR 友好:大部分函数支持服务端渲染
  • 持续更新:活跃的社区维护

1.3 安装与使用

bash 复制代码
# 使用 npm
npm install @vueuse/core

# 使用 pnpm(推荐)
pnpm add @vueuse/core

按需引入(推荐):

vue 复制代码
<script setup>
import { useMouse, useLocalStorage, useDebounceFn } from '@vueuse/core'

// 只引入需要的函数
const { x, y } = useMouse()
const settings = useLocalStorage('settings', { theme: 'light' })
</script>

完整引入(不推荐,会增大包体积):

typescript 复制代码
import VueUse from '@vueuse/core'
// 或
import * as VueUse from '@vueuse/core'

二、状态管理工具

2.1 useLocalStorage / useSessionStorage

持久化存储状态,自动同步到 localStorage/sessionStorage:

vue 复制代码
<script setup>
import { useLocalStorage, useSessionStorage } from '@vueuse/core'

// 基本用法:key + 默认值
const settings = useLocalStorage('app-settings', {
  theme: 'light',
  language: 'zh-CN',
  fontSize: 16
})

// 类型安全(泛型)
const user = useLocalStorage<User>('user', null)

// 使用 sessionStorage
const sessionData = useSessionStorage('session-key', { timestamp: Date.now() })

// 监听变化
watch(settings, (newSettings) => {
  console.log('设置已更新', newSettings)
})
</script>

<template>
  <select v-model="settings.theme">
    <option value="light">亮色</option>
    <option value="dark">暗色</option>
  </select>
  <select v-model="settings.language">
    <option value="zh-CN">中文</option>
    <option value="en-US">English</option>
  </select>
  <input type="number" v-model.number="settings.fontSize" />
</template>

高级选项:

typescript 复制代码
import { useLocalStorage } from '@vueuse/core'

// 自定义序列化/反序列化
const data = useLocalStorage('key', { count: 0 }, {
  serializer: {
    read: (v: string) => v ? JSON.parse(v) : null,
    write: (v: any) => JSON.stringify(v)
  },
  deep: true,  // 深度监听变化
  flush: 'post' // 更新时机
})

2.2 useStorage

统一处理 localStorage 和 sessionStorage:

typescript 复制代码
import { useStorage } from '@vueuse/core'

// 默认使用 localStorage
const token = useStorage('token', '')

// 指定使用 sessionStorage
const sessionToken = useStorage('session-token', '', sessionStorage)

2.3 useRefHistory

跟踪响应式状态的变更历史:

typescript 复制代码
import { ref } from 'vue'
import { useRefHistory } from '@vueuse/core'

const state = ref({ count: 0, name: 'Vue' })
const { history, undo, redo, canUndo, canRedo, clear } = useRefHistory(state, {
  deep: true,
  capacity: 10  // 最多保存 10 条历史
})

function increment() {
  state.value.count++
}

function undoLast() {
  if (canUndo.value) {
    undo()
  }
}

2.4 useAsyncState

管理异步状态:

typescript 复制代码
import { useAsyncState } from '@vueuse/core'

// 基本用法
const { state, isLoading, error, execute } = useAsyncState(
  async () => {
    const response = await fetch('/api/users')
    return response.json()
  },
  [],  // 初始状态
  {
    immediate: true,  // 立即执行
    resetOnExecute: false,  // 执行时是否重置状态
    onSuccess: (data) => console.log('成功', data),
    onError: (err) => console.error('失败', err)
  }
)

// 手动执行
function refreshUsers() {
  execute()
}

2.5 useDebounceFn / useThrottleFn

防抖和节流函数:

vue 复制代码
<script setup>
import { ref } from 'vue'
import { useDebounceFn, useThrottleFn } from '@vueuse/core'

const searchKeyword = ref('')
const searchResults = ref([])

// 防抖:用户停止输入 500ms 后执行搜索
const debouncedSearch = useDebounceFn(async (keyword: string) => {
  if (!keyword.trim()) {
    searchResults.value = []
    return
  }
  const data = await api.search(keyword)
  searchResults.value = data
}, 500)

// 节流:滚动事件最多每 200ms 执行一次
const handleScroll = useThrottleFn(() => {
  console.log('滚动位置', window.scrollY)
}, 200)

function onInput(event: Event) {
  const value = (event.target as HTMLInputElement).value
  searchKeyword.value = value
  debouncedSearch(value)
}
</script>

<template>
  <input @input="onInput" placeholder="搜索..." />
  <div @scroll="handleScroll" class="scrollable">
    <!-- 内容 -->
  </div>
</template>

2.6 useDebouncedRef / useThrottledRef

防抖/节流的响应式引用:

typescript 复制代码
import { useDebouncedRef, useThrottledRef } from '@vueuse/core'

// 防抖 ref:变化 300ms 后才更新
const debouncedText = useDebouncedRef('', 300)

// 节流 ref:最多每 500ms 更新一次
const throttledValue = useThrottledRef(0, 500)

watch(debouncedText, (newVal) => {
  console.log('防抖后的值', newVal)
})

三、DOM 操作工具

3.1 useMouse / useMouseInElement

监听鼠标位置:

vue 复制代码
<script setup>
import { useMouse, useMouseInElement } from '@vueuse/core'

// 全局鼠标位置
const { x, y } = useMouse()
// 鼠标在文档中的位置

// 相对于指定元素的鼠标位置
const elementRef = ref<HTMLElement | null>(null)
const { x: elementX, y: elementY, isOutside } = useMouseInElement(elementRef)
</script>

<template>
  <p>鼠标位置:{{ x }}, {{ y }}</p>
  <div ref="elementRef" style="width: 300px; height: 200px; border: 1px solid #ccc;">
    鼠标在元素内:{{ !isOutside }},位置:{{ elementX }}, {{ elementY }}
  </div>
</template>

3.2 useWindowSize / useElementSize

监听窗口/元素尺寸:

vue 复制代码
<script setup>
import { ref } from 'vue'
import { useWindowSize, useElementSize } from '@vueuse/core'

// 窗口尺寸
const { width, height } = useWindowSize()

// 元素尺寸
const elementRef = ref<HTMLElement | null>(null)
const { width: elWidth, height: elHeight } = useElementSize(elementRef)
</script>

<template>
  <p>窗口:{{ width }} × {{ height }}</p>
  <div ref="elementRef" style="resize: both; overflow: auto; border: 1px solid #ccc;">
    <p>元素尺寸:{{ elWidth }} × {{ elHeight }}</p>
  </div>
</template>

3.3 useIntersectionObserver

监听元素可见性(懒加载、无限滚动):

vue 复制代码
<script setup>
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'

const targetRef = ref<HTMLElement | null>(null)
const isVisible = ref(false)

useIntersectionObserver(
  targetRef,
  ([{ isIntersecting }]) => {
    isVisible.value = isIntersecting
    if (isIntersecting) {
      console.log('元素进入视口,可以加载数据了')
    }
  },
  {
    threshold: 0.5,  // 50% 可见时触发
    rootMargin: '100px'  // 提前 100px 触发
  }
)
</script>

<template>
  <div style="height: 1000px;"></div>
  <div ref="targetRef" style="height: 200px; background: #4299e1; color: white; padding: 20px;">
    {{ isVisible ? '👀 可见' : '🙈 不可见' }}
  </div>
</template>

3.4 useScroll

监听滚动位置:

typescript 复制代码
import { useScroll } from '@vueuse/core'

// 监听窗口滚动
const { x, y, isScrolling, arrivedState, directions } = useScroll(window)

// 监听元素滚动
const containerRef = ref<HTMLElement | null>(null)
const { x: scrollX, y: scrollY } = useScroll(containerRef)

console.log('滚动方向', directions)  // { left, right, up, down }
console.log('是否到达边界', arrivedState)  // { left, right, top, bottom }

3.5 useFocus / useFocusWithin

管理焦点状态:

vue 复制代码
<script setup>
import { useFocus, useFocusWithin } from '@vueuse/core'

const inputRef = ref<HTMLInputElement | null>(null)
const isFocused = useFocus(inputRef)

const containerRef = ref<HTMLElement | null>(null)
const isFocusWithin = useFocusWithin(containerRef)
</script>

<template>
  <input ref="inputRef" :class="{ focused: isFocused }" />
  <div ref="containerRef">
    <input placeholder="焦点在容器内" />
    <input placeholder="焦点在容器内" />
    <p>容器内是否有焦点:{{ isFocusWithin }}</p>
  </div>
</template>

3.6 useClipboard

剪贴板操作:

vue 复制代码
<script setup>
import { useClipboard } from '@vueuse/core'

const { text, copy, isSupported, copied } = useClipboard({
  source: '',  // 要复制的文本
  copiedDuring: 2000  // 复制成功状态持续时间
})

async function copyText(textToCopy: string) {
  await copy(textToCopy)
  if (copied.value) {
    console.log('复制成功!')
  }
}
</script>

<template>
  <p v-if="!isSupported">浏览器不支持剪贴板 API</p>
  <button @click="copyText('Hello VueUse!')">复制文本</button>
  <span v-if="copied">✅ 已复制</span>
</template>

四、浏览器 API 工具

4.1 useOnline / useNetwork

监听网络状态:

vue 复制代码
<script setup>
import { useOnline, useNetwork } from '@vueuse/core'

const isOnline = useOnline()
const { isOnline: networkOnline, downlink, effectiveType } = useNetwork()
</script>

<template>
  <div>
    <p>在线状态:{{ isOnline ? '🟢 在线' : '🔴 离线' }}</p>
    <p v-if="isOnline">网络类型:{{ effectiveType }}</p>
    <p v-if="isOnline">下行速度:{{ downlink }} Mbps</p>
  </div>
</template>

4.2 useGeolocation

获取地理位置:

vue 复制代码
<script setup>
import { useGeolocation } from '@vueuse/core'

const { coords, locatedAt, error, isSupported } = useGeolocation()

watch(coords, (newCoords) => {
  if (newCoords) {
    console.log('纬度', newCoords.latitude)
    console.log('经度', newCoords.longitude)
  }
})
</script>

<template>
  <div v-if="isSupported">
    <p v-if="coords">
      位置:{{ coords.latitude }}, {{ coords.longitude }}
      <br />精度:{{ coords.accuracy }} 米
    </p>
    <p v-else>正在获取位置...</p>
    <p v-if="error">{{ error.message }}</p>
  </div>
  <p v-else>浏览器不支持地理定位</p>
</template>

4.3 usePermission

检查浏览器权限:

typescript 复制代码
import { usePermission } from '@vueuse/core'

const cameraPermission = usePermission('camera')
const geolocationPermission = usePermission('geolocation')
const notificationsPermission = usePermission('notifications')

watch(cameraPermission, (status) => {
  console.log('摄像头权限', status)  // 'granted' | 'denied' | 'prompt'
})

4.4 useFullscreen

全屏控制:

vue 复制代码
<script setup>
import { ref } from 'vue'
import { useFullscreen } from '@vueuse/core'

const elementRef = ref<HTMLElement | null>(null)
const { isFullscreen, enter, exit, toggle } = useFullscreen(elementRef)
</script>

<template>
  <div ref="elementRef">
    <h2>全屏演示</h2>
    <p>当前状态:{{ isFullscreen ? '全屏中' : '非全屏' }}</p>
    <button @click="toggle">
      {{ isFullscreen ? '退出全屏' : '进入全屏' }}
    </button>
  </div>
</template>

4.5 useMediaQuery / usePreferredDark

响应式媒体查询:

vue 复制代码
<script setup>
import { useMediaQuery, usePreferredDark, usePreferredColorScheme } from '@vueuse/core'

// 响应式断点
const isMobile = useMediaQuery('(max-width: 640px)')
const isTablet = useMediaQuery('(min-width: 641px) and (max-width: 1024px)')
const isDesktop = useMediaQuery('(min-width: 1025px)')

// 系统偏好
const prefersDark = usePreferredDark()
const prefersColorScheme = usePreferredColorScheme()
</script>

<template>
  <div>
    <p>设备类型:{{ isMobile ? '📱 手机' : isTablet ? '📟 平板' : '🖥️ 桌面' }}</p>
    <p>系统主题偏好:{{ prefersDark ? '🌙 深色' : '☀️ 亮色' }}</p>
    <p>系统颜色方案:{{ prefersColorScheme }}</p>
  </div>
</template>

4.6 useVibrate

设备震动(移动端):

typescript 复制代码
import { useVibrate } from '@vueuse/core'

// 震动 100ms
const { isSupported, vibrate, stop } = useVibrate()

function notifyVibrate() {
  if (isSupported.value) {
    vibrate([100, 50, 100, 50, 200])  // 震动模式:100ms震动,50ms暂停,100ms震动...
  }
}

五、动画与时间工具

5.1 useInterval

定时执行:

typescript 复制代码
import { useInterval } from '@vueuse/core'

// 每秒执行
const counter = ref(0)
const { pause, resume, isActive } = useInterval(() => {
  counter.value++
}, 1000)

// 或使用响应式轮询
const count = useInterval(1000)  // 返回一个 ref,每秒递增

5.2 useTimeout

延迟执行:

typescript 复制代码
import { useTimeout } from '@vueuse/core'

// 3 秒后变为 true
const ready = useTimeout(3000)

// 可重置
const { ready: isReady, start, stop } = useTimeout(5000, { controls: true })

function restartTimer() {
  stop()
  start()
}

5.3 useRafFn

基于 requestAnimationFrame 的动画:

typescript 复制代码
import { useRafFn } from '@vueuse/core'

const progress = ref(0)
const isRunning = ref(false)

const { pause, resume } = useRafFn(() => {
  if (progress.value < 1) {
    progress.value += 0.01
  } else {
    pause()
  }
}, { immediate: false })

function startAnimation() {
  progress.value = 0
  resume()
}

5.4 useTransition

值过渡动画:

vue 复制代码
<script setup>
import { ref } from 'vue'
import { useTransition } from '@vueuse/core'

const source = ref(0)
const animatedValue = useTransition(source, {
  duration: 1000,
  easing: (t) => t * t * (3 - 2 * t),  // easeInOut
  transition: 'smooth'
})

function jumpTo(value: number) {
  source.value = value
}
</script>

<template>
  <input type="range" min="0" max="100" v-model="source" />
  <div class="progress-bar" :style="{ width: animatedValue + '%' }">
    {{ Math.round(animatedValue) }}%
  </div>
</template>

5.5 useTimestamp

响应式时间戳:

typescript 复制代码
import { useTimestamp } from '@vueuse/core'

// 每秒更新
const now = useTimestamp({ interval: 1000 })
console.log(now.value)  // 当前时间戳

// 格式化为时间字符串
const timeString = computed(() => {
  return new Date(now.value).toLocaleTimeString()
})

六、网络请求工具

6.1 useFetch

简化 HTTP 请求:

vue 复制代码
<script setup>
import { useFetch } from '@vueuse/core'

// 基础用法
const { data, isLoading, error, execute } = useFetch('/api/users')
  .json()

// 带配置
const { data: userData, isLoading: userLoading } = useFetch('/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: '张三' })
}).json()

// 链式调用
const { data: products } = useFetch('/api/products')
  .get()
  .json()

// 手动执行
const { data: searchResults, execute: search } = useFetch('/api/search')
  .get()
  .json()
  .immediate(false)  // 不立即执行

function doSearch(keyword: string) {
  search({ params: { q: keyword } })
}
</script>

<template>
  <div v-if="isLoading">加载中...</div>
  <div v-else-if="error">错误:{{ error.message }}</div>
  <div v-else>{{ data }}</div>
</template>

6.2 useWebSocket

WebSocket 连接:

vue 复制代码
<script setup>
import { useWebSocket } from '@vueuse/core'

const { status, data, send, open, close } = useWebSocket('wss://echo.websocket.org')

function sendMessage(message: string) {
  send(message)
}

watch(data, (newData) => {
  console.log('收到消息', newData)
})
</script>

<template>
  <p>连接状态:{{ status }}</p>
  <button @click="sendMessage('Hello')">发送消息</button>
  <button @click="close">断开</button>
  <button @click="open">连接</button>
</template>

七、SSR 工具

7.1 useHydrated / useMounted

处理 SSR 中的客户端挂载:

vue 复制代码
<script setup>
import { useMounted, useHydrated } from '@vueuse/core'

// 检查组件是否已在客户端挂载
const isMounted = useMounted()

// 检查 hydration 是否完成
const isHydrated = useHydrated()
</script>

<template>
  <!-- 仅在客户端渲染的内容 -->
  <div v-if="isMounted">
    这个内容只在客户端显示
  </div>
  
  <!-- Hydration 完成前显示占位 -->
  <div v-if="!isHydrated" class="placeholder">
    加载中...
  </div>
  <div v-else>
    真实内容
  </div>
</template>

7.2 usePreferredMediaQuery

服务器端兼容的媒体查询:

typescript 复制代码
import { usePreferredMediaQuery } from '@vueuse/core'

// 在 SSR 中,在客户端生效前使用默认值
const isDark = usePreferredMediaQuery('(prefers-color-scheme: dark)', {
  defaultValue: false  // SSR 时默认值
})

八、自定义 VueUse 风格组合式函数

8.1 设计原则

VueUse 风格的组合式函数遵循以下原则:

  1. 以 use 开头
  2. 返回响应式对象或 ref
  3. 支持 controls 选项返回控制方法
  4. 支持 immediate 选项控制是否立即执行
  5. 在组件卸载时自动清理资源
  6. 完善的 TypeScript 类型

8.2 示例:useLocalStorageWithExpiry

typescript 复制代码
// composables/useLocalStorageWithExpiry.ts
import { ref, watch, onMounted, type Ref } from 'vue'

interface StorageOptions {
  expiry?: number  // 过期时间(毫秒)
  serializer?: {
    read: (v: string) => any
    write: (v: any) => string
  }
}

export function useLocalStorageWithExpiry<T>(
  key: string,
  defaultValue: T,
  options: StorageOptions = {}
): Ref<T> {
  const { expiry = 0, serializer = JSON } = options
  
  const data = ref<T>(defaultValue) as Ref<T>
  
  // 读取存储
  function readFromStorage(): T {
    try {
      const item = localStorage.getItem(key)
      if (!item) return defaultValue
      
      const parsed = serializer.read(item)
      
      // 检查是否包含过期时间
      if (parsed && typeof parsed === 'object' && parsed._expiry) {
        if (Date.now() > parsed._expiry) {
          localStorage.removeItem(key)
          return defaultValue
        }
        return parsed.value
      }
      
      return parsed
    } catch {
      return defaultValue
    }
  }
  
  // 写入存储
  function writeToStorage(value: T) {
    try {
      const toStore = expiry > 0
        ? { value, _expiry: Date.now() + expiry }
        : value
      localStorage.setItem(key, serializer.write(toStore))
    } catch (e) {
      console.warn('写入 localStorage 失败', e)
    }
  }
  
  // 初始化
  onMounted(() => {
    data.value = readFromStorage()
  })
  
  // 监听变化
  watch(data, (newValue) => {
    writeToStorage(newValue)
  }, { deep: true })
  
  return data
}

8.3 示例:useWindowEvent

typescript 复制代码
// composables/useWindowEvent.ts
import { onMounted, onUnmounted } from 'vue'

export function useWindowEvent<K extends keyof WindowEventMap>(
  event: K,
  handler: (event: WindowEventMap[K]) => void,
  options?: AddEventListenerOptions
) {
  function cleanup() {
    window.removeEventListener(event, handler as any, options)
  }
  
  onMounted(() => {
    window.addEventListener(event, handler as any, options)
  })
  
  onUnmounted(() => {
    cleanup()
  })
  
  return { cleanup }
}

使用:

vue 复制代码
<script setup>
import { useWindowEvent } from '@/composables/useWindowEvent'

useWindowEvent('resize', () => {
  console.log('窗口大小变化', window.innerWidth)
})

useWindowEvent('keydown', (e) => {
  if (e.key === 'Escape') {
    console.log('按下了 ESC 键')
  }
})
</script>

8.4 示例:useBreakpoints(带 SSR 支持)

typescript 复制代码
// composables/useBreakpoints.ts
import { ref, onMounted, onUnmounted } from 'vue'

interface Breakpoints {
  xs: string
  sm: string
  md: string
  lg: string
  xl: string
  '2xl': string
}

const defaultBreakpoints: Breakpoints = {
  xs: '0px',
  sm: '640px',
  md: '768px',
  lg: '1024px',
  xl: '1280px',
  '2xl': '1536px'
}

export function useBreakpoints(breakpoints: Breakpoints = defaultBreakpoints) {
  const current = ref<string>('xs')
  const matches = ref<Record<keyof Breakpoints, boolean>>({
    xs: false,
    sm: false,
    md: false,
    lg: false,
    xl: false,
    '2xl': false
  })
  
  function update() {
    const width = window.innerWidth
    const entries = Object.entries(breakpoints) as [keyof Breakpoints, string][]
    
    // 从大到小排序
    const sorted = entries.sort((a, b) => {
      const aVal = parseInt(a[1])
      const bVal = parseInt(b[1])
      return bVal - aVal
    })
    
    let found = 'xs'
    for (const [key, value] of sorted) {
      const minWidth = parseInt(value)
      if (width >= minWidth) {
        found = key
        break
      }
    }
    
    current.value = found
    
    // 更新所有匹配状态
    entries.forEach(([key, value]) => {
      const minWidth = parseInt(value)
      matches.value[key] = width >= minWidth
    })
  }
  
  let cleanup: (() => void) | null = null
  
  onMounted(() => {
    update()
    window.addEventListener('resize', update)
    cleanup = () => window.removeEventListener('resize', update)
  })
  
  onUnmounted(() => {
    if (cleanup) cleanup()
  })
  
  return {
    current,
    matches,
    // 便捷属性
    isXs: () => current.value === 'xs',
    isSm: () => current.value === 'sm',
    isMd: () => current.value === 'md',
    isLg: () => current.value === 'lg',
    isXl: () => current.value === 'xl',
    is2xl: () => current.value === '2xl',
    // 最小尺寸
    minSm: () => matches.value.sm,
    minMd: () => matches.value.md,
    minLg: () => matches.value.lg,
    minXl: () => matches.value.xl,
    min2xl: () => matches.value['2xl']
  }
}

九、综合实战:响应式仪表板

让我们综合运用 VueUse 的多个工具,构建一个实时仪表板:

vue 复制代码
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  useMouse,
  useWindowSize,
  useOnline,
  useLocalStorage,
  useIntersectionObserver,
  useDebounceFn,
  useInterval,
  useFetch,
  useTimestamp
} from '@vueuse/core'

// -------- 状态管理 --------
const settings = useLocalStorage('dashboard-settings', {
  showMouseTracker: true,
  showNetworkStatus: true,
  refreshInterval: 5000
})

// -------- 鼠标位置 --------
const { x, y } = useMouse()

// -------- 窗口尺寸 --------
const { width, height } = useWindowSize()

// -------- 网络状态 --------
const isOnline = useOnline()

// -------- 时间 --------
const now = useTimestamp({ interval: 1000 })
const timeString = computed(() => {
  return new Date(now.value).toLocaleString('zh-CN')
})

// -------- 数据获取 --------
const { data: stats, isLoading, error, execute: fetchStats } = useFetch('/api/dashboard-stats')
  .json()
  .immediate(false)

// -------- 定时刷新 --------
useInterval(() => {
  fetchStats()
}, settings.value.refreshInterval)

// -------- 懒加载 --------
const sectionRef = ref<HTMLElement | null>(null)
const isSectionVisible = ref(false)

useIntersectionObserver(
  sectionRef,
  ([{ isIntersecting }]) => {
    isSectionVisible.value = isIntersecting
    if (isIntersecting) {
      console.log('图表区域可见,开始渲染')
    }
  },
  { threshold: 0.3 }
)

// -------- 防抖搜索 --------
const searchKeyword = ref('')
const searchResults = ref([])

const debouncedSearch = useDebounceFn(async (keyword: string) => {
  if (!keyword.trim()) {
    searchResults.value = []
    return
  }
  const data = await fetch(`/api/search?q=${keyword}`).then(r => r.json())
  searchResults.value = data
}, 300)

function onSearchInput(event: Event) {
  const value = (event.target as HTMLInputElement).value
  searchKeyword.value = value
  debouncedSearch(value)
}

// -------- 计算属性 --------
const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 6) return '🌙 夜深了'
  if (hour < 9) return '🌅 早上好'
  if (hour < 12) return '☀️ 上午好'
  if (hour < 14) return '🌤️ 中午好'
  if (hour < 18) return '🌤️ 下午好'
  if (hour < 21) return '🌅 傍晚好'
  return '🌙 晚上好'
})

// -------- 组件挂载时加载数据 --------
onMounted(() => {
  fetchStats()
})
</script>

<template>
  <div class="dashboard">
    <!-- 标题栏 -->
    <header class="dashboard-header">
      <h1>{{ greeting }},仪表板</h1>
      <div class="header-stats">
        <span>🕐 {{ timeString }}</span>
        <span :class="['status', { online: isOnline, offline: !isOnline }]">
          {{ isOnline ? '🟢 在线' : '🔴 离线' }}
        </span>
        <span>📐 {{ width }} × {{ height }}</span>
        <span v-if="settings.showMouseTracker">🖱️ {{ Math.round(x) }}, {{ Math.round(y) }}</span>
      </div>
    </header>

    <!-- 搜索框 -->
    <div class="search-section">
      <input
        v-model="searchKeyword"
        @input="onSearchInput"
        placeholder="🔍 搜索..."
        class="search-input"
      />
      <div v-if="searchResults.length > 0" class="search-results">
        <div v-for="item in searchResults" :key="item.id" class="search-result">
          {{ item.name }}
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card" v-if="!isLoading">
        <span class="stat-label">总用户</span>
        <span class="stat-value">{{ stats?.totalUsers || 0 }}</span>
      </div>
      <div class="stat-card" v-if="!isLoading">
        <span class="stat-label">活跃用户</span>
        <span class="stat-value">{{ stats?.activeUsers || 0 }}</span>
      </div>
      <div class="stat-card" v-if="!isLoading">
        <span class="stat-label">今日订单</span>
        <span class="stat-value">{{ stats?.todayOrders || 0 }}</span>
      </div>
      <div class="stat-card" v-if="!isLoading">
        <span class="stat-label">总收入</span>
        <span class="stat-value">¥{{ stats?.totalRevenue || 0 }}</span>
      </div>
    </div>

    <!-- 懒加载图表 -->
    <div ref="sectionRef" class="chart-section">
      <h2>📊 数据趋势</h2>
      <div v-if="isSectionVisible" class="chart-placeholder">
        <!-- 实际项目中用 ECharts 等图表库 -->
        <div class="chart-bars">
          <div v-for="i in 12" :key="i" class="chart-bar-wrapper">
            <div
              class="chart-bar"
              :style="{ height: (20 + Math.random() * 80) + '%' }"
            >
              <span class="bar-value">{{ Math.round(20 + Math.random() * 80) }}</span>
            </div>
          </div>
        </div>
        <p class="chart-tip">💡 图表在进入视口时加载</p>
      </div>
      <div v-else class="chart-placeholder">⏳ 滚动到此处加载图表...</div>
    </div>

    <!-- 设置 -->
    <div class="settings-section">
      <h3>⚙️ 设置</h3>
      <label>
        <input v-model="settings.showMouseTracker" type="checkbox" />
        显示鼠标位置
      </label>
      <label>
        <input v-model="settings.showNetworkStatus" type="checkbox" />
        显示网络状态
      </label>
      <label>
        刷新间隔:
        <select v-model.number="settings.refreshInterval">
          <option :value="3000">3 秒</option>
          <option :value="5000">5 秒</option>
          <option :value="10000">10 秒</option>
          <option :value="30000">30 秒</option>
        </select>
      </label>
    </div>
  </div>
</template>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  background: #f8fafc;
  min-height: 100vh;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  padding: 16px 20px;
  background: white;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.06);
}
.dashboard-header h1 { font-size: 24px; margin: 0; }
.header-stats {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #718096;
}
.header-stats .status { font-weight: 600; }
.header-stats .online { color: #48bb78; }
.header-stats .offline { color: #fc8181; }

.search-section {
  position: relative;
  margin-bottom: 24px;
}
.search-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 10px;
  font-size: 16px;
  transition: border-color 0.2s;
}
.search-input:focus {
  outline: none;
  border-color: #4299e1;
}
.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border-radius: 0 0 10px 10px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  max-height: 300px;
  overflow-y: auto;
  z-index: 10;
}
.search-result {
  padding: 10px 16px;
  border-bottom: 1px solid #edf2f7;
  cursor: pointer;
}
.search-result:hover { background: #f7fafc; }

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}
.stat-card {
  background: white;
  padding: 20px 24px;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.06);
}
.stat-label { font-size: 14px; color: #718096; }
.stat-value { font-size: 28px; font-weight: 700; color: #1a202c; display: block; }

.chart-section {
  background: white;
  border-radius: 12px;
  padding: 20px 24px;
  margin-bottom: 24px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.06);
}
.chart-section h2 { font-size: 18px; margin-top: 0; }

.chart-placeholder {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #a0aec0;
}
.chart-bars {
  display: flex;
  height: 150px;
  align-items: flex-end;
  gap: 8px;
  width: 100%;
  justify-content: center;
}
.chart-bar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  height: 100%;
  justify-content: flex-end;
}
.chart-bar {
  width: 100%;
  max-width: 40px;
  background: linear-gradient(to top, #4299e1, #63b3ed);
  border-radius: 4px 4px 0 0;
  min-height: 10px;
  position: relative;
}
.bar-value {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 11px;
  color: #4a5568;
}
.chart-tip {
  text-align: center;
  font-size: 13px;
  color: #a0aec0;
  margin-top: 8px;
}

.settings-section {
  background: white;
  border-radius: 12px;
  padding: 20px 24px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.06);
}
.settings-section h3 { font-size: 16px; margin-top: 0; }
.settings-section label {
  display: block;
  padding: 6px 0;
  font-size: 14px;
  color: #4a5568;
}
.settings-section input[type="checkbox"] {
  margin-right: 8px;
  accent-color: #4299e1;
}
.settings-section select {
  padding: 4px 8px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  margin-left: 8px;
}

@media (max-width: 768px) {
  .stats-grid { grid-template-columns: repeat(2, 1fr); }
  .dashboard-header { flex-direction: column; align-items: stretch; }
  .header-stats { flex-wrap: wrap; gap: 8px; }
}
</style>

十、VueUse 与 Pinia 的结合

10.1 在 Pinia Store 中使用 VueUse

typescript 复制代码
// stores/theme.ts
import { defineStore } from 'pinia'
import { useLocalStorage, usePreferredDark, useMediaQuery } from '@vueuse/core'

export const useThemeStore = defineStore('theme', () => {
  // 持久化用户偏好
  const userPreference = useLocalStorage<'light' | 'dark' | 'system'>('theme-preference', 'system')
  
  // 系统偏好
  const prefersDark = usePreferredDark()
  
  // 媒体查询监听
  const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)')
  
  // 计算实际主题
  const currentTheme = computed(() => {
    if (userPreference.value === 'system') {
      return isDarkMode.value ? 'dark' : 'light'
    }
    return userPreference.value
  })
  
  function setTheme(theme: 'light' | 'dark' | 'system') {
    userPreference.value = theme
  }
  
  function toggleTheme() {
    if (currentTheme.value === 'light') {
      setTheme('dark')
    } else {
      setTheme('light')
    }
  }
  
  return {
    userPreference,
    currentTheme,
    isDarkMode,
    setTheme,
    toggleTheme
  }
})

10.2 在组件中组合使用

vue 复制代码
<script setup>
import { storeToRefs } from 'pinia'
import { useThemeStore } from '@/stores/theme'
import { useDebounceFn, useMouse } from '@vueuse/core'

const themeStore = useThemeStore()
const { currentTheme, isDarkMode } = storeToRefs(themeStore)
const { toggleTheme } = themeStore

const { x, y } = useMouse()

// 防抖处理主题切换
const debouncedToggle = useDebounceFn(toggleTheme, 300)
</script>

<template>
  <div :data-theme="currentTheme">
    <button @click="debouncedToggle">
      {{ isDarkMode ? '🌙' : '☀️' }} 切换主题
    </button>
    <p>鼠标位置:{{ x }}, {{ y }}</p>
  </div>
</template>

十一、常见问题与解决方案

11.1 SSR 兼容性问题

VueUse 的大部分函数在 SSR 中都能正常工作,但某些依赖浏览器 API 的函数需要特殊处理:

typescript 复制代码
// ❌ 在 SSR 中可能报错
const { width, height } = useWindowSize()

// ✅ 使用 useHydrated 或 useMounted 保护
const isMounted = useMounted()
const windowSize = computed(() => {
  if (!isMounted.value) return { width: 0, height: 0 }
  return useWindowSize()
})

11.2 内存泄漏

VueUse 的函数会在组件卸载时自动清理资源,但如果手动创建了监听器,需要确保清理:

typescript 复制代码
// VueUse 自动管理清理
const { pause, resume } = useInterval(() => {}, 1000)

// 手动清理示例
const { stop } = useEventListener('resize', handler)
// 组件卸载时自动调用 stop

11.3 性能优化

typescript 复制代码
// 使用 shallowRef 避免深层响应式
const largeData = useLocalStorage('data', [], {
  deep: false  // 浅层监听,提升性能
})

// 使用 debounce 减少频繁更新
const debouncedSearch = useDebounceFn(search, 300)

十二、本篇小结

分类 核心工具 用途
状态管理 useLocalStorage、useRefHistory、useAsyncState 持久化、历史追踪、异步状态
DOM 操作 useMouse、useIntersectionObserver、useScroll 鼠标、可见性、滚动
浏览器 API useOnline、useGeolocation、useFullscreen 网络、位置、全屏
动画/时间 useInterval、useTransition、useRafFn 定时器、过渡动画、帧动画
网络请求 useFetch、useWebSocket HTTP 请求、WebSocket
SSR useMounted、useHydrated 客户端挂载检测
自定义 按需封装组合式函数 复用业务逻辑

十三、思考与练习

  1. 基础练习 :使用 useLocalStorage 实现一个"最近搜索"功能,保存用户最近的 5 条搜索记录。

  2. 实践任务 :使用 useIntersectionObserver 和 useFetch 实现一个无限滚动列表,当滚动到底部时自动加载更多数据。

  3. 深度思考:VueUse 的设计哲学是什么?它和 React Hooks 的工具库(如 ahooks)有什么异同?

  4. 扩展任务 :仿照 VueUse 的风格,封装一个 useCountdown 组合式函数,支持倒计时、暂停、恢复和重置功能。

下篇预告

第 25 篇我们将进入原理源码篇,开始深入 Vue 的底层原理:

  • 响应式系统原理------从 Object.defineProperty 到 Proxy
  • 依赖收集(track)与触发更新(trigger)机制
  • Reflect 的深层属性追踪

准备好深入 Vue 的底层世界!🔍

相关推荐
GuWenyue14 分钟前
setInterval 里的 state 永远是 0?我把 React 闭包陷阱的 5 个反例全写了一遍
前端·react.js
Xeni21 分钟前
从「会写」到「真懂」:SSE 流式输出的 20 行代码与 7 个坑
前端
bai27330 分钟前
字段一个不差,md5 却对不上:对象键顺序的三条规则
前端·javascript
map_3d_vis1 小时前
百度地图 2.0 / 3.0 项目升级到 JSAPI 4.0:改一个参数
前端·javascript·地图·百度地图
亿元程序员1 小时前
别人家的蚂蚁搬家游戏一周赚1.6万?我反省了一下我的...
前端
用户69371750013841 小时前
AI 用久了,我发现自己越来越不想找人聊天了
前端·后端·github
恋猫de小郭1 小时前
Flutter Perfetto:Dart Heap Sampling 终于要接入 Android 原生内存分析了
android·前端·flutter
Highcharts.js3 小时前
Highcharts 在商业智能中的实战应用:释放数据洞察
前端·人工智能·算法·信息可视化·数据分析·数据可视化·highcharts