Skip to content

2026-07-08 学习笔记

Vue 3 组合式 API 复习

重新梳理了组合式 API 的核心概念,做了些练习。

核心 API 回顾

typescript
// ref - 基本类型响应式
const count = ref(0)

// computed - 计算属性
const double = computed(() => count.value * 2)

// watch - 监听变化
watch(count, (newVal, oldVal) => {
  console.log(`${oldVal} → ${newVal}`)
})

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

组合式函数封装

typescript
// composables/useFetch.ts
export function useFetch<T>(url: string) {
  const data = ref<T | null>(null)
  const loading = ref(true)
  const error = ref<Error | null>(null)

  fetch(url)
    .then(res => res.json())
    .then(json => { data.value = json })
    .catch(err => { error.value = err })
    .finally(() => { loading.value = false })

  return { data, loading, error }
}

心得

组合式函数的核心价值是逻辑复用代码组织。一个函数只做一件事,命名以 use 开头,这就是 Vue 3 的最佳实践。


组合式 API 让代码更灵活,但也要避免过度抽象。

阅读量

基于 VitePress 构建