目录

Vue3组合式API深度解析

组合式API(Composition API)是 Vue3 最重要的特性之一,它让逻辑复用和代码组织变得更加灵活。

为什么需要组合式API?

在 Vue2 的 Options API 中,组件逻辑分散在 data、methods、computed 等选项中。当组件变得复杂时,相关逻辑被拆散到不同位置,难以维护。组合式API允许我们按功能组织代码。

ref vs reactive

javascript
import { ref, reactive } from 'vue';

// ref 适用于基本类型
const count = ref(0);
count.value++;

// reactive 适用于对象
const state = reactive({
  user: { name: '星野樱', age: 18 },
  list: []
});
state.user.name = '月见里';

选择建议

  • 基本类型使用 ref
  • 对象/数组使用 reactive
  • 需要解构时使用 ref(reactive 解构会失去响应性)

computed 计算属性

javascript
import { ref, computed } from 'vue';

const price = ref(100);
const quantity = ref(3);

const total = computed(() => price.value * quantity.value);

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

watch 侦听器

javascript
import { ref, watch, watchEffect } from 'vue';

const keyword = ref('');

// watch 需要明确指定侦听源
watch(keyword, (newVal, oldVal) => {
  console.log(`从 ${oldVal} 变为 ${newVal}`);
}, { immediate: true, deep: true });

// watchEffect 自动收集依赖
watchEffect(() => {
  console.log(`当前关键词: ${keyword.value}`);
});

生命周期钩子

Options API Composition API
beforeCreate setup()
created setup()
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted

自定义 Composable

将逻辑提取为可复用的函数:

javascript
// composables/useMouse.js
import { ref, onMounted, onUnmounted } from 'vue';

export function useMouse() {
  const x = ref(0);
  const y = ref(0);

  function update(event) {
    x.value = event.pageX;
    y.value = event.pageY;
  }

  onMounted(() => window.addEventListener('mousemove', update));
  onUnmounted(() => window.removeEventListener('mousemove', update));

  return { x, y };
}

在组件中使用:

vue


<template>
  <p>鼠标位置: {{ x }}, {{ y }}</p>
</template>

provide / inject 跨层级传递

javascript
// 父组件
import { provide, ref } from 'vue';
const theme = ref('dark');
provide('theme', theme);

// 子组件
import { inject } from 'vue';
const theme = inject('theme', 'light');

总结

组合式API的核心优势在于逻辑复用和代码组织。通过 Composable 函数,我们可以像搭积木一样组合功能,写出更清晰、更易维护的代码。