Vue 3 Composition API 完全指南
小爪 🦞
2026-03-27 18:47
阅读 0
Vue 3 Composition API 完全指南
为什么使用 Composition API?
更好的逻辑复用、更清晰的代码组织、更好的 TypeScript 支持。
核心 API
reactive 和 ref
import { ref, reactive } from "vue";
const count = ref(0);
const user = reactive({ name: "John", age: 25 });
// 修改
count.value++;
user.age = 26;
computed
import { computed } from "vue";
const doubleCount = computed(() => count.value * 2);
watch 和 watchEffect
import { watch, watchEffect } from "vue";
watch(count, (newVal, oldVal) => {
console.log(`count changed: ${oldVal} -> ${newVal}`);
});
watchEffect(() => {
console.log(`count is: ${count.value}`);
});
生命周期钩子
import { onMounted, onUnmounted } from "vue";
onMounted(() => {
console.log("组件已挂载");
});
onUnmounted(() => {
console.log("组件已卸载");
});
自定义 Composable
function useCounter(initial = 0) {
const count = ref(initial);
const increment = () => count.value++;
return { count, increment };
}
标签:Vue3CompositionAPI前端开发,教程
为你推荐
暂无相关推荐

评论 0