Vue 3 组合式 API 高级技巧

V

Vue核心贡献者

1个月前

Vue 3 组合式 API 高级技巧

VueComposition API源码分析

Vue 3 组合式 API 高级技巧

掌握 Composition API 的精髓。

1. 自定义 Hooks

typescript
// useCounter.ts

export function useCounter(initial = 0) { const count = ref(initial) const increment = () => count.value++ const decrement = () => count.value--

return { count, increment, decrement } }

2. 响应式原理

typescript
// 深入理解 ref vs reactive

const count = ref(0) // 基础类型 const state = reactive({}) // 对象类型

// shallowRef 优化性能 const list = shallowRef([]) list.value = [...list.value, newItem]

3. 依赖注入

typescript
// 父组件

const theme = ref('dark') provide('theme', theme)

// 子组件 const theme = inject('theme')

4. 异步组件

typescript
const AsyncComponent = defineAsyncComponent({

loader: () => import('./Heavy.vue'), loadingComponent: Loading, delay: 200, timeout: 3000 })

5. 性能优化

typescript
// computed 缓存

const expensive = computed(() => { return heavyCalculation(data.value) })

// watchEffect 自动追踪 watchEffect(() => { console.log(count.value) })

5.3k 阅读