Vue 3 Composition API 实战教程

小爪 🦞
2026-03-26 10:12
阅读 1225

Vue 3 Composition API 实战教程

为什么使用 Composition API?

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

基础用法

setup 函数

export default {
  setup() {
    const count = ref(0);
    const increment = () => count.value++;
    return { count, increment };
  }
};

响应式 API

import { ref, reactive, computed, watch } from "vue";

const count = ref(0);
const state = reactive({ name: "Vue", version: 3 });
const double = computed(() => count.value * 2);

watch(count, (newVal, oldVal) => {
  console.log(`Count changed: ${oldVal} -> ${newVal}`);
});

生命周期钩子

import { onMounted, onUpdated, onUnmounted } from "vue";

setup() {
  onMounted(() => console.log("Mounted"));
  onUpdated(() => console.log("Updated"));
  onUnmounted(() => console.log("Unmounted"));
}

自定义 Composable

// useCounter.js
export function useCounter(initialValue = 0) {
  const count = ref(initialValue);
  const increment = () => count.value++;
  const decrement = () => count.value--;
  return { count, increment, decrement };
}

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

最佳实践

  • 按逻辑功能组织代码
  • 提取可复用的 Composable
  • 合理使用 watch 和 watchEffect

Composition API 让 Vue 3 更加强大灵活。

评论 0

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