VueUse Composable Utilities Library
VueUse is a utility library based on the Vue 3 Composition API, offering a wide range of out-of-the-box composable functions that cover common frontend development needs. From state management to browser API encapsulation, and even animations and utility tools, it significantly enhances development efficiency.
Core Features
The core design philosophy of VueUse is "composable reuse." It provides a series of atomic functions, allowing developers to build complex features like assembling building blocks. These functions are fully based on Vue's reactivity system, automatically handling dependency tracking and lifecycle management.
import { useMouse, useLocalStorage } from '@vueuse/core'
// Track mouse position
const { x, y } = useMouse()
// Automatic local storage synchronization
const count = useLocalStorage('my-count', 0)
Common Functional Modules
State Management
VueUse offers multiple state management solutions, more convenient than using ref
/reactive
directly:
import { useStorage, useToggle } from '@vueuse/core'
// Automatically sync with localStorage
const state = useStorage('user-settings', {
theme: 'dark',
notifications: true
})
// Boolean toggle
const [isDark, toggleDark] = useToggle(false)
Browser API Integration
Encapsulates common browser APIs, giving them reactive properties:
import { useGeolocation, useClipboard } from '@vueuse/core'
// Geolocation
const { coords, locatedAt } = useGeolocation()
// Clipboard operations
const { copy, isSupported } = useClipboard()
DOM Manipulation
Simplifies common DOM manipulation patterns:
import { useElementSize, useScroll } from '@vueuse/core'
const el = ref(null)
const { width, height } = useElementSize(el)
const { x, y, isScrolling } = useScroll(window)
Advanced Usage
Function Composition
VueUse functions can be freely combined like Lego bricks:
import { useMouse, useThrottleFn, useDebounceFn } from '@vueuse/core'
const { x, y } = useMouse()
// Throttle handling
const throttledX = useThrottleFn(x, 500)
// Debounce handling
const debouncedY = useDebounceFn(y, 300)
Reactive Utilities
Provides practical tools for reactive programming:
import { useCounter, useIntervalFn } from '@vueuse/core'
const { count, inc, dec } = useCounter(0)
// Timer
const { pause, resume } = useIntervalFn(() => inc(), 1000)
Performance Optimization
VueUse includes built-in performance optimization techniques:
import { useIntersectionObserver, useIdle } from '@vueuse/core'
// Lazy loading
const target = ref(null)
useIntersectionObserver(target, ([{ isIntersecting }]) => {
if (isIntersecting) {
// Load resources
}
})
// User idle detection
const { idle } = useIdle(5000)
Custom Extensions
While VueUse already offers rich functionality, it can be easily extended:
import { createSharedComposable } from '@vueuse/core'
// Create a shared composable function
function useSharedCounter() {
const count = ref(0)
const inc = () => count.value++
return { count, inc }
}
export const useCounter = createSharedComposable(useSharedCounter)
Integration with Other Libraries
VueUse seamlessly integrates with other popular libraries:
import { useAxios } from '@vueuse/integrations/useAxios'
import axios from 'axios'
const { data, isLoading } = useAxios('/api/user')
Practical Use Cases
Form Enhancement
import { useVModel, useValidation } from '@vueuse/core'
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
// Simplified two-way binding
const value = useVModel(props, 'modelValue', emit)
// Form validation
const { isEmail } = useValidation()
const emailValid = computed(() => isEmail(value.value))
Animation Effects
import { useTransition, useRafFn } from '@vueuse/core'
const source = ref(0)
const output = useTransition(source, {
duration: 1000,
transition: [0.75, 0, 0.25, 1]
})
// Animation loop
useRafFn(() => {
source.value = Math.sin(Date.now() / 1000) * 100
})
Type Safety
VueUse is entirely written in TypeScript, providing comprehensive type definitions:
import { useMouse } from '@vueuse/core'
const { x, y } = useMouse() // x and y are automatically inferred as Ref<number>
Ecosystem
The VueUse ecosystem includes multiple extension packages:
@vueuse/components
: Provides composable components@vueuse/motion
: Animation solutions@vueuse/sound
: Audio processing@vueuse/firebase
: Firebase integration
import { useMotion } from '@vueuse/motion'
const target = ref(null)
useMotion(target, {
initial: { opacity: 0 },
enter: { opacity: 1, x: 0 },
leave: { opacity: 0, x: 100 }
})
Best Practices
- Import on Demand: Avoid full imports to reduce bundle size.
- Composable Reuse: Combine multiple VueUse functions into custom hooks.
- Lifecycle Management: Be mindful of automatically cleaned-up side effects.
- Reactive Conversion: Use
toRefs
to maintain reactivity.
import { watchOnce, toRefs } from '@vueuse/core'
const props = defineProps(['user'])
const { user } = toRefs(props)
// One-time watch
watchOnce(user, (newUser) => {
console.log('User changed:', newUser)
})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:Pinia状态管理