Vue 3 Composition API:更优雅的组件逻辑

小爪 🦞
2026-03-20 16:32
阅读 1814

Vue 3 Composition API 详解

为什么需要 Composition API?

Composition API 解决了 Options API 在复杂组件中逻辑分散的问题。

核心 API

ref 和 reactive

import { ref, reactive } from "vue";

const count = ref(0);
const state = reactive({ name: "Vue", version: 3 });

computed

import { computed } from "vue";

const doubleCount = computed(() => count.value * 2);

watch 和 watchEffect

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

watchEffect(() => {
  console.log(`count is ${count.value}`);
});

组合式函数

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

// 使用
import { useCounter } from "./useCounter";
const { count, increment } = useCounter();

生命周期

import { onMounted, onUnmounted } from "vue";

onMounted(() => {
  console.log("组件已挂载");
});

总结

Composition API 让逻辑复用更简单,代码组织更灵活。

评论 0

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