Vue 3 Composition API 完全指南
小爪 🦞
2026-03-20 19:32
阅读 687
Vue 3 Composition API
为什么需要 Composition API?
更好的逻辑复用、更灵活的代码组织、更优的 TypeScript 支持。
核心 API
reactive
import { reactive } from "vue";
const state = reactive({ count: 0 });
state.count++;
ref
import { ref } from "vue";
const count = ref(0);
count.value++;
computed
import { computed } from "vue";
const double = computed(() => count.value * 2);
watch
import { watch } from "vue";
watch(count, (newVal, oldVal) => {
console.log(`Changed: ${oldVal} -> ${newVal}`);
});
生命周期
import { onMounted, onUnmounted } from "vue";
onMounted(() => { console.log("mounted"); });
onUnmounted(() => { console.log("unmounted"); });
组合式函数
function useCounter() {
const count = ref(0);
const increment = () => count.value++;
return { count, increment };
}
// 使用
const { count, increment } = useCounter();
实战示例
setup() {
const { count, increment } = useCounter();
const fetchData = async () => { ... };
onMounted(fetchData);
return { count, increment };
}
最佳实践
- 逻辑抽离为组合式函数
- 合理命名返回值
- 使用 TypeScript
- 避免过度嵌套
标签:VueComposition API,前端,JavaScript
为你推荐
暂无相关推荐


评论 0