好的,阿杰 👍
我来给你整理一份 Vue 3 Composition API 详解,包含概念、常用 API、示例和对比。
Vue 3 Composition API 详解
1. 什么是 Composition API
- Vue 2:主要使用 Options API(
data
、methods
、computed
、watch
等),代码按“选项”组织。 - Vue 3:引入 Composition API,通过函数组合来组织逻辑,适合复杂逻辑复用。
👉 核心思想:关注逻辑功能(composition),而不是选项分类。
2. 基本用法
在组件中使用 setup()
:
<script setup>
import { ref } from 'vue'
// 响应式变量
const count = ref(0)
// 方法
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">Count: {{ count }}</button>
</template>
ref()
:定义响应式数据(基本类型)reactive()
:定义响应式对象- 通过
.value
访问/修改ref
3. 常用 API
3.1 响应式
import { ref, reactive, computed } from 'vue'
const message = ref("Hello")
const state = reactive({ count: 0 })
const double = computed(() => state.count * 2)
3.2 生命周期
import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
console.log("组件挂载完成")
})
onUnmounted(() => {
console.log("组件卸载")
})
对应关系:
Options API | Composition API |
---|---|
created | setup() 内代码 |
mounted | onMounted |
beforeUnmount | onBeforeUnmount |
unmounted | onUnmounted |
3.3 侦听
import { ref, watch, watchEffect } from 'vue'
const count = ref(0)
watch(count, (newVal, oldVal) => {
console.log(`count: ${oldVal} -> ${newVal}`)
})
watchEffect(() => {
console.log("count 改变时自动执行: ", count.value)
})
3.4 Props 与 Emit
<script setup>
import { defineProps, defineEmits } from 'vue'
const props = defineProps({
title: String
})
const emit = defineEmits(['update'])
function updateTitle() {
emit('update', '新的标题')
}
</script>
<template>
<h1>{{ props.title }}</h1>
<button @click="updateTitle">更新标题</button>
</template>
3.5 Provide / Inject
适合跨层级传递数据:
// 父组件
import { provide, ref } from 'vue'
const count = ref(0)
provide('count', count)
// 子组件
import { inject } from 'vue'
const count = inject('count')
3.6 自定义 Hook(逻辑复用)
// useCounter.js
import { ref } from 'vue'
export function useCounter() {
const count = ref(0)
const increment = () => count.value++
return { count, increment }
}
<script setup>
import { useCounter } from './useCounter'
const { count, increment } = useCounter()
</script>
<template>
<button @click="increment">Count: {{ count }}</button>
</template>
👉 类似 React 的 Hooks。
4. Options API vs Composition API
特点 | Options API | Composition API |
---|---|---|
写法 | data / methods / computed | ref / reactive / setup() |
逻辑复用 | Mixins / HOC | 自定义 hooks |
代码组织 | 按功能块分散(data、methods 分开) | 按逻辑聚合(相关逻辑集中) |
学习曲线 | 上手简单 | 灵活,但初学复杂 |
5. 小结
- ref/ reactive:定义响应式数据
- computed / watch / watchEffect:派生数据与侦听
- 生命周期钩子:
onMounted
等 - 逻辑复用:自定义 Hook(函数化逻辑抽取)
- 适用场景:复杂逻辑、可复用性需求高的项目
发表回复