VueUse组合式工具库
VueUse 是一个基于 Vue 3 Composition API 的工具库,提供了大量开箱即用的组合式函数,覆盖了常见的前端开发需求。从状态管理到浏览器 API 封装,再到动画和实用工具,它能够显著提升开发效率。
核心特性
VueUse 的核心设计理念是"组合式复用"。它通过一系列原子化的函数,让开发者能够像搭积木一样构建复杂功能。这些函数完全基于 Vue 的响应式系统,自动处理依赖追踪和生命周期。
import { useMouse, useLocalStorage } from '@vueuse/core'
// 鼠标位置跟踪
const { x, y } = useMouse()
// 本地存储自动同步
const count = useLocalStorage('my-count', 0)
常用功能模块
状态管理
VueUse 提供了多种状态管理方案,比直接使用 ref/reactive 更加便捷:
import { useStorage, useToggle } from '@vueuse/core'
// 自动同步到 localStorage
const state = useStorage('user-settings', {
theme: 'dark',
notifications: true
})
// 布尔值切换
const [isDark, toggleDark] = useToggle(false)
浏览器 API 集成
封装了常见的浏览器 API,使其具备响应式特性:
import { useGeolocation, useClipboard } from '@vueuse/core'
// 地理位置
const { coords, locatedAt } = useGeolocation()
// 剪贴板操作
const { copy, isSupported } = useClipboard()
DOM 操作
简化了常见的 DOM 操作模式:
import { useElementSize, useScroll } from '@vueuse/core'
const el = ref(null)
const { width, height } = useElementSize(el)
const { x, y, isScrolling } = useScroll(window)
高级用法
函数组合
VueUse 函数可以像乐高积木一样自由组合:
import { useMouse, useThrottleFn, useDebounceFn } from '@vueuse/core'
const { x, y } = useMouse()
// 节流处理
const throttledX = useThrottleFn(x, 500)
// 防抖处理
const debouncedY = useDebounceFn(y, 300)
响应式工具
提供了一些响应式编程的实用工具:
import { useCounter, useIntervalFn } from '@vueuse/core'
const { count, inc, dec } = useCounter(0)
// 定时器
const { pause, resume } = useIntervalFn(() => inc(), 1000)
性能优化
VueUse 内置了多种性能优化手段:
import { useIntersectionObserver, useIdle } from '@vueuse/core'
// 懒加载
const target = ref(null)
useIntersectionObserver(target, ([{ isIntersecting }]) => {
if (isIntersecting) {
// 加载资源
}
})
// 用户空闲检测
const { idle } = useIdle(5000)
自定义扩展
虽然 VueUse 已经提供了丰富功能,但也可以轻松扩展:
import { createSharedComposable } from '@vueuse/core'
// 创建共享组合函数
function useSharedCounter() {
const count = ref(0)
const inc = () => count.value++
return { count, inc }
}
export const useCounter = createSharedComposable(useSharedCounter)
与其他库集成
VueUse 可以无缝与其他流行库配合使用:
import { useAxios } from '@vueuse/integrations/useAxios'
import axios from 'axios'
const { data, isLoading } = useAxios('/api/user')
实际应用场景
表单增强
import { useVModel, useValidation } from '@vueuse/core'
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
// 双向绑定简化
const value = useVModel(props, 'modelValue', emit)
// 表单验证
const { isEmail } = useValidation()
const emailValid = computed(() => isEmail(value.value))
动画效果
import { useTransition, useRafFn } from '@vueuse/core'
const source = ref(0)
const output = useTransition(source, {
duration: 1000,
transition: [0.75, 0, 0.25, 1]
})
// 动画循环
useRafFn(() => {
source.value = Math.sin(Date.now() / 1000) * 100
})
类型安全
VueUse 完全使用 TypeScript 编写,提供了完善的类型定义:
import { useMouse } from '@vueuse/core'
const { x, y } = useMouse() // x 和 y 自动推断为 Ref<number>
生态系统
VueUse 的生态系统包含多个扩展包:
@vueuse/components
:提供可组合的组件@vueuse/motion
:动画解决方案@vueuse/sound
:音频处理@vueuse/firebase
:Firebase 集成
import { useMotion } from '@vueuse/motion'
const target = ref(null)
useMotion(target, {
initial: { opacity: 0 },
enter: { opacity: 1, x: 0 },
leave: { opacity: 0, x: 100 }
})
最佳实践
- 按需导入:避免全量导入减小打包体积
- 组合复用:将多个 VueUse 函数组合成自定义 hook
- 生命周期:注意自动清理的副作用
- 响应式转换:利用
toRefs
保持响应式
import { watchOnce, toRefs } from '@vueuse/core'
const props = defineProps(['user'])
const { user } = toRefs(props)
// 只触发一次的监听
watchOnce(user, (newUser) => {
console.log('User changed:', newUser)
})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:Pinia状态管理