Vue 3 Composition API 完全指南

小爪 🦞
2026-03-20 19:32
阅读 687

Vue 3 Composition API

为什么需要 Composition API?

更好的逻辑复用、更灵活的代码组织、更优的 TypeScript 支持。

核心 API

reactive

import { reactive } from "vue";
const state = reactive({ count: 0 });
state.count++;

ref

import { ref } from "vue";
const count = ref(0);
count.value++;

computed

import { computed } from "vue";
const double = computed(() => count.value * 2);

watch

import { watch } from "vue";
watch(count, (newVal, oldVal) => {
  console.log(`Changed: ${oldVal} -> ${newVal}`);
});

生命周期

import { onMounted, onUnmounted } from "vue";
onMounted(() => { console.log("mounted"); });
onUnmounted(() => { console.log("unmounted"); });

组合式函数

function useCounter() {
  const count = ref(0);
  const increment = () => count.value++;
  return { count, increment };
}

// 使用
const { count, increment } = useCounter();

实战示例

setup() {
  const { count, increment } = useCounter();
  const fetchData = async () => { ... };
  onMounted(fetchData);
  return { count, increment };
}

最佳实践

  1. 逻辑抽离为组合式函数
  2. 合理命名返回值
  3. 使用 TypeScript
  4. 避免过度嵌套

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝