name: vueuse description: 在使用VueUse组合式函数时使用 - 提供状态、浏览器API、传感器、网络、动画等的响应式实用工具。在编写自定义组合式函数之前检查VueUse - 大多数模式已经实现。 license: MIT
VueUse
Vue组合式实用工具的集合。在编写自定义组合式函数之前检查VueUse - 大多数模式已经实现。
当前稳定版: VueUse 14.x 用于 Vue 3.5+
安装
Vue 3:
pnpm add @vueuse/core
Nuxt:
pnpm add @vueuse/nuxt @vueuse/core
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@vueuse/nuxt'],
})
Nuxt模块自动导入组合式函数 - 无需手动导入。
类别
| 类别 | 示例 |
|---|---|
| 状态 | useLocalStorage, useSessionStorage, useRefHistory |
| 元素 | useElementSize, useIntersectionObserver, useResizeObserver |
| 浏览器 | useClipboard, useFullscreen, useMediaQuery |
| 传感器 | useMouse, useKeyboard, useDeviceOrientation |
| 网络 | useFetch, useWebSocket, useEventSource |
| 动画 | useTransition, useInterval, useTimeout |
| 组件 | useVModel, useVirtualList, useTemplateRefsList |
| 监听 | watchDebounced, watchThrottled, watchOnce |
| 响应式 | createSharedComposable, toRef, toReactive |
| 数组 | useArrayFilter, useArrayMap, useSorted |
| 时间 | useDateFormat, useNow, useTimeAgo |
| 实用工具 | useDebounce, useThrottle, useMemoize |
快速参考
根据需要加载组合式文件:
| 正在处理… | 加载文件 |
|---|---|
| 查找组合式函数 | references/composables.md |
| 特定组合式函数 | composables/<name>.md |
加载文件
根据您的任务考虑加载这些参考文件:
- [ ] references/composables.md - 如果按类别或功能搜索VueUse组合式函数
不要一次性加载所有文件。 只加载与当前任务相关的文件。
常见模式
状态持久化:
const state = useLocalStorage('my-key', { count: 0 })
鼠标跟踪:
const { x, y } = useMouse()
防抖引用:
const search = ref('')
const debouncedSearch = refDebounced(search, 300)
共享组合式函数(单例):
const useSharedMouse = createSharedComposable(useMouse)
SSR 注意事项
许多VueUse组合式函数使用在SSR期间不可用的浏览器API。
使用 isClient 检查:
import { isClient } from '@vueuse/core'
if (isClient) {
// 仅限浏览器的代码
const { width } = useWindowSize()
}
包装在 onMounted 中:
const width = ref(0)
onMounted(() => {
// 仅在浏览器中运行
const { width: w } = useWindowSize()
width.value = w.value
})
使用 SSR 安全的组合式函数:
// 这些在内部检查 isClient
const mouse = useMouse() // 在服务器上返回 {x: 0, y: 0}
const storage = useLocalStorage('key', 'default') // 在服务器上使用默认值
@vueuse/nuxt 自动处理 SSR - 组合式函数在服务器上返回安全默认值。
目标元素引用
当目标组件引用而不是DOM元素时:
import type { MaybeElementRef } from '@vueuse/core'
// 组件引用需要 .$el 来获取DOM元素
const compRef = ref<ComponentInstance>()
const { width } = useElementSize(compRef) // ❌ 不会工作
// 使用 MaybeElementRef 模式
import { unrefElement } from '@vueuse/core'
const el = computed(() => unrefElement(compRef)) // 获取 .$el
const { width } = useElementSize(el) // ✅ 工作
或直接访问 $el:
const compRef = ref<ComponentInstance>()
onMounted(() => {
const el = compRef.value?.$el as HTMLElement
const { width } = useElementSize(el)
})