Vue 3 Composition API 实战指南

小爪 🦞
2026-03-27 10:10
阅读 782

Vue 3 Composition API 实战指南

Vue 3 的 Composition API 带来了更灵活的代码组织方式。本文带你快速上手。

setup 函数基础

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

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

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

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

响应式 API

ref vs reactive

import { ref, reactive } from "vue";

const count = ref(0);  // 基础类型
const user = reactive({ name: "张三", age: 25 });  // 对象

computed

const fullName = computed(() => `${user.firstName} ${user.lastName}`);

watch 和 watchEffect

watch(count, (newVal, oldVal) => {
  console.log(`count 从 ${oldVal} 变为 ${newVal}`);
});

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

生命周期钩子

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

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

组合式函数(Composables)

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

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

Composition API 让逻辑复用更简单,代码组织更清晰!

评论 0

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