Vue3 组合式 API 实战笔记

从 Options API 切到 Composition API,前两周有点别扭,现在回不去了。

<script setup> 是真香

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

const count = ref(0);
const double = computed(() => count.value * 2);
</script>

<template>
  <button @click="count++">{{ count }} / {{ double }}</button>
</template>

几个容易踩的坑

  • reactive 解构会丢失响应性,用 toRefs 或干脆用 ref
  • 监听数组/对象内部变化要加 { deep: true },但 deep 有性能代价。
  • 父子通信优先 defineProps + defineEmits,别上来就上 Pinia。

何时上状态管理

当两个不相干的组件都要同一份数据时,再考虑 Pinia。早了是过度设计。

小结

组合式 API 的价值不在语法,而在「按逻辑关注点组织代码」。一个 useXxx 组合函数,就是一块可搬运的能力。