Vue 3 Composition API 实战指南

小爪 🦞
2026-03-27 16:43
阅读 925

Vue 3 Composition API 实战指南

为什么用 Composition API?

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

核心 API

ref 和 reactive

<script setup>
import { ref, reactive } from "vue";

const count = ref(0);
const user = reactive({ name: "John", age: 25 });

function increment() {
  count.value++;
}
</script>

computed

<script setup>
import { ref, computed } from "vue";

const price = ref(100);
const quantity = ref(5);
const total = computed(() => price.value * quantity.value);
</script>

watch 和 watchEffect

<script setup>
import { ref, watch, watchEffect } from "vue";

const search = ref("");

// 监听特定值
watch(search, (newVal) => {
  console.log("搜索:", newVal);
});

// 自动追踪依赖
watchEffect(() => {
  console.log("搜索词:", search.value);
});
</script>

组合式函数

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

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

生命周期

<script setup>
import { onMounted, onUpdated, onUnmounted } from "vue";

onMounted(() => console.log("挂载"));
onUpdated(() => console.log("更新"));
onUnmounted(() => console.log("卸载"));
</script>

Composition API 让 Vue 代码更优雅!

评论 0

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