更灵活的代码组织
按功能而非选项分组
组合式 API 让你可以更灵活地组织代码,像搭积木一样!🧱
<script setup>import { ref, computed, watch } from 'vue'
// 响应式状态const count = ref(0)const double = computed(() => count.value * 2)
// 方法function increment() { count.value++}
// 侦听器watch(count, (newVal) => { console.log('Count changed:', newVal)})</script>
<template> <button @click="increment"> {{ count }} x 2 = {{ double }} ✨ </button></template><script setup>import { onMounted, onUnmounted } from 'vue'
onMounted(() => { console.log('组件已挂载!🎉')})
onUnmounted(() => { console.log('组件已卸载!👋')})</script>import { ref } from 'vue'
export function useCounter() { const count = ref(0)
function increment() { count.value++ }
return { count, increment }}更灵活的代码组织
按功能而非选项分组
更好的类型推断
TypeScript 支持更友好
逻辑复用
通过组合式函数复用逻辑
更小的包体积
更好的 Tree-shaking