← 返回文档目录

文档阅读

本文档介绍 Vue3 组合式 API 的核心概念,帮助你快速上手 Vue3 开发。

1. 组合式 API 基础

Vue3 引入了组合式 API(Composition API),通过 setup() 函数或 <script setup> 语法糖来组织逻辑。

<script setup>
import { ref, computed } from 'vue'

const count = ref(0)
const doubled = computed(() => count.value * 2)

function increment() {
  count.value++
}
</script>

2. 响应式数据

使用 ref() 包装基础类型,使用 reactive() 包装对象:

import { ref, reactive } from 'vue'

const name = ref('世界')         // 基础类型
const user = reactive({          // 对象类型
  id: 1,
  email: 'hello@example.com'
})

3. 计算属性和侦听器

import { ref, computed, watch } from 'vue'

const price = ref(100)
const quantity = ref(2)
const total = computed(() => price.value * quantity.value)

watch(quantity, (newVal, oldVal) => {
  console.log(`数量从 ${oldVal} 变为 ${newVal}`)
})

4. 生命周期

import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  console.log('组件已挂载')
})

onUnmounted(() => {
  console.log('组件已卸载')
})

最后更新:2026-04-18