Vue3组合式API完全指南


Vue3组合式API完全指南

Vue3最大的变化之一就是引入了组合式API(Composition API),它彻底改变了我们组织组件逻辑的方式。与选项式API相比,组合式API提供了更好的代码组织、更灵活的逻辑复用和更优秀的TypeScript支持。本文将全面介绍组合式API的核心概念和实战技巧。

一、从选项式到组合式

选项式API按照选项类型组织代码,而组合式API按照逻辑功能组织代码:

// 选项式API - 按选项类型组织
export default {
  data() {
    return { count: 0, user: null }
  },
  computed: {
    doubleCount() { return this.count * 2 }
  },
  methods: {
    increment() { this.count++ }
  },
  mounted() { this.fetchUser() }
}

// 组合式API - 按逻辑功能组织
import { ref, computed, onMounted } from 'vue'

export default {
  setup() {
    // 计数器逻辑
    const count = ref(0)
    const doubleCount = computed(() => count.value * 2)
    const increment = () => count.value++

    // 用户逻辑
    const user = ref(null)
    onMounted(async () => { user.value = await fetchUser() })

    return { count, doubleCount, increment, user }
  }
}

二、响应式核心:ref与reactive

// ref - 用于基本类型和任意值
const count = ref(0)
const user = ref({ name: '张三' })
console.log(count.value)  // 需要使用.value

// reactive - 用于对象类型
const state = reactive({
  count: 0,
  user: { name: '张三' }
})
console.log(state.count)  // 直接访问

// 注意:reactive不能替换整个对象
// state = { count: 1 } // 错误!丢失响应式

// 推荐使用ref,更灵活
const state = ref({ count: 0, user: { name: '张三' } })
state.value = { count: 1 } // OK

三、计算属性与侦听器

import { ref, computed, watch, watchEffect } from 'vue'

const firstName = ref('')
const lastName = ref('')

// 计算属性
const fullName = computed({
  get: () => firstName.value + ' ' + lastName.value,
  set: (val) => {
    [firstName.value, lastName.value] = val.split(' ')
  }
})

// watch - 精确控制
watch(firstName, (newVal, oldVal) => {
  console.log('名字变了', newVal)
}, { immediate: true, deep: true })

// watchEffect - 自动追踪依赖
watchEffect(() => {
  console.log('全名:', firstName.value, lastName.value)
})

四、组合式函数(Composables)

组合式函数是组合式API最强大的特性,可以实现优雅的逻辑复用:

// useCounter.js
import { ref, computed } from 'vue'

export function useCounter(initialValue = 0) {
  const count = ref(initialValue)
  const doubled = computed(() => count.value * 2)
  const increment = () => count.value++
  const decrement = () => count.value--
  const reset = () => count.value = initialValue
  return { count, doubled, increment, decrement, reset }
}

// useFetch.js - 通用数据请求
export function useFetch(url) {
  const data = ref(null)
  const error = ref(null)
  const loading = ref(false)

  const execute = async () => {
    loading.value = true
    try {
      const response = await fetch(url)
      data.value = await response.json()
    } catch (e) {
      error.value = e
    } finally {
      loading.value = false
    }
  }

  execute()
  return { data, error, loading, execute }
}

// 在组件中使用
import { useCounter } from './useCounter'
import { useFetch } from './useFetch'

const { count, doubled, increment } = useCounter(10)
const { data: users, loading } = useFetch('/api/users')

五、生命周期钩子

import { 
  onBeforeMount, onMounted,
  onBeforeUpdate, onUpdated,
  onBeforeUnmount, onUnmounted,
  onActivated, onDeactivated
} from 'vue'

onBeforeMount(() => console.log('挂载前'))
onMounted(() => console.log('已挂载'))
onBeforeUpdate(() => console.log('更新前'))
onUpdated(() => console.log('已更新'))
onBeforeUnmount(() => console.log('卸载前'))
onUnmounted(() => console.log('已卸载'))

Vue3的组合式API为开发者提供了更灵活、更强大的代码组织方式。掌握组合式函数的编写和复用,是成为Vue3高级开发者的关键。


0.049584s