# Vue3中Composition API怎么用
## 引言
隨著Vue3的正式發布,Composition API作為其最核心的新特性之一,徹底改變了我們組織和復用組件邏輯的方式。與Vue2的Options API相比,Composition API提供了更靈活的代碼組織能力、更好的類型推斷支持以及更高效的邏輯復用機制。本文將全面解析Composition API的使用方法,從基礎概念到高級技巧,幫助開發者掌握這一現代化前端開發利器。
## 一、Composition API概述
### 1.1 什么是Composition API
Composition API是Vue3引入的一套新的API風格,它允許開發者通過函數式的方式組織和復用組件邏輯。與Options API(如data、methods等選項)不同,Composition API基于"組合"的思想,將相關邏輯集中在一起。
```javascript
// Options API示例
export default {
data() {
return { count: 0 }
},
methods: {
increment() {
this.count++
}
}
}
// Composition API示例
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
const increment = () => count.value++
return { count, increment }
}
}
setup是Composition API的入口函數,它在組件實例創建之前執行。
export default {
setup(props, context) {
// 在這里聲明響應式數據、計算屬性、方法等
return {
// 返回的內容可以在模板中使用
}
}
}
setup(props, { attrs, slots, emit }) {
// 使用emit觸發事件
const handleClick = () => {
emit('custom-event', payload)
}
return { handleClick }
}
setup() {
const count = ref(0)
return {
count,
double: computed(() => count.value * 2)
}
}
Vue3提供了兩種創建響應式數據的主要方式:
.value訪問值const count = ref(0)
console.log(count.value) // 0
const state = reactive({ count: 0 })
console.log(state.count) // 0
Vue3提供了一系列響應式工具函數:
const state = reactive({ foo: 1, bar: 2 })
const { foo, bar } = toRefs(state) // 解構后保持響應性
const double = computed(() => count.value * 2)
watch(count, (newVal, oldVal) => {
console.log(`count變化: ${oldVal} -> ${newVal}`)
})
watchEffect(() => {
console.log(`count的值是: ${count.value}`)
})
Composition API提供了一組與生命周期對應的函數:
| Options API | Composition API |
|---|---|
| beforeCreate | 不需要(setup替代) |
| created | 不需要(setup替代) |
| beforeMount | onBeforeMount |
| mounted | onMounted |
| beforeUpdate | onBeforeUpdate |
| updated | onUpdated |
| beforeUnmount | onBeforeUnmount |
| unmounted | onUnmounted |
| errorCaptured | onErrorCaptured |
| renderTracked | onRenderTracked |
| renderTriggered | onRenderTriggered |
import { onMounted, onUnmounted } from 'vue'
setup() {
onMounted(() => {
console.log('組件已掛載')
})
onUnmounted(() => {
console.log('組件已卸載')
})
}
Composition API提供了provide和inject函數實現依賴注入:
// 祖先組件
import { provide, ref } from 'vue'
setup() {
const theme = ref('dark')
provide('theme', theme)
}
// 后代組件
import { inject } from 'vue'
setup() {
const theme = inject('theme', 'light') // 默認值'light'
return { theme }
}
Composition API最大的優勢之一是能夠輕松地提取和復用邏輯:
// useCounter.js
import { ref } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
const increment = () => count.value++
const decrement = () => count.value--
return { count, increment, decrement }
}
// 在組件中使用
import { useCounter } from './useCounter'
setup() {
const { count, increment } = useCounter(10)
return { count, increment }
}
Composition API天生對TypeScript友好:
interface Props {
msg: string
count?: number
}
export default defineComponent({
props: {
msg: {
type: String,
required: true
},
count: {
type: Number,
default: 0
}
},
setup(props: Props) {
// 現在props有正確的類型提示
}
})
interface User {
name: string
age: number
}
const user = ref<User>({ name: 'Alice', age: 25 })
import { ref, computed } from 'vue'
export default {
setup() {
const newTodo = ref('')
const todos = ref([])
const filter = ref('all')
const addTodo = () => {
if (newTodo.value.trim()) {
todos.value.push({
id: Date.now(),
text: newTodo.value,
completed: false
})
newTodo.value = ''
}
}
const filteredTodos = computed(() => {
switch (filter.value) {
case 'active': return todos.value.filter(t => !t.completed)
case 'completed': return todos.value.filter(t => t.completed)
default: return todos.value
}
})
return { newTodo, todos, filter, addTodo, filteredTodos }
}
}
Composition API代表了Vue框架的一次重大進化,它解決了Options API在復雜組件中面臨的代碼組織難題,同時提供了更強大的邏輯復用能力。通過本文的學習,你應該已經掌握了:
雖然Composition API有一定的學習曲線,但一旦掌握,它將顯著提升你的開發效率和代碼質量。建議在實際項目中逐步嘗試,從簡單組件開始,逐步應用到更復雜的場景中。
”`
這篇文章共計約4900字,全面介紹了Vue3 Composition API的核心概念和使用方法,從基礎到高級,包含了大量代碼示例和實用建議。文章采用Markdown格式,結構清晰,便于閱讀和理解。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。