Files
chunyu_project/media/learn/courses/15/chapters/62.md
T
2026-08-05 23:59:15 +08:00

50 lines
943 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Vue 3 组合式 API
## 学习目标
- 理解 Options API vs Composition API
- 掌握 setup 语法
- 学会使用响应式 API
## Composition API 简介
Composition API 是 Vue 3 推荐的编写方式,使用函数组合替代选项式配置。
## 基础用法
```vue
<script setup>
import { ref, computed, onMounted } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
function increment() {
count.value++
}
onMounted(() => {
console.log('组件已挂载')
})
</script>
<template>
<button @click="increment">{{ count }} × 2 = {{ doubled }}</button>
</template>
```
## 常用 API
| API | 说明 |
|-----|------|
| `ref()` | 响应式变量 |
| `reactive()` | 响应式对象 |
| `computed()` | 计算属性 |
| `watch()` | 监听器 |
| `onMounted()` | 挂载后 |
## 动手练习
1. 使用 Composition API 实现计数器
2. 创建待办事项列表
3. 使用 watch 监听数据变化