记录 Vue 3 中 Composition API 的基本使用方式,重点包括 ref
、reactive
和 setup()
的使用细节。
一、setup() 基础
Vue 3 中的逻辑入口从 data
等 Options API 移到了 setup()
函数中。
<script>
export default {
setup() {
// 这里是组件逻辑
}
}
</script>
在 <script setup>
中,这一步可以省略,直接写逻辑。
二、ref 用于基本数据类型
ref()
用来创建响应式的基本类型变量,例如数字、字符串、布尔值。
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">点击 {{ count }}</button>
</template>
注意 .value
是必须的访问方式。
三、reactive 用于对象或数组
reactive()
用来处理对象和数组的响应式。
<script setup>
import { reactive } from 'vue'
const form = reactive({
username: '',
age: 0
})
function update() {
form.age += 1
}
</script>
<template>
<div>
<input v-model="form.username" />
<p>{{ form.username }} - {{ form.age }}</p>
<button @click="update">增长年龄</button>
</div>
</template>
直接修改对象属性即可自动触发视图更新。
四、ref vs reactive 的区别
特性 | ref | reactive |
---|---|---|
适用类型 | 基本类型 | 对象 / 数组 |
响应方式 | 值包裹在 .value 中 |
直接响应式代理 |
解构后失去响应性 | 是 | 是 |
与模板配合 | 模板中自动解包 .value |
模板中可直接使用 |
五、组合使用场景
可以将 reactive
和 ref
混用:
const user = reactive({
name: 'Tom',
age: ref(18) // 嵌套 ref
})
六、defineExpose / defineProps 简介
在 <script setup>
中,如需向外暴露方法、接收 props,可以用:
defineProps(['title'])
defineExpose({
focus: () => { /* ... */ }
})
这些都是组合式 API 的一部分。
七、小结
ref
用于基本类型,reactive
用于对象和数组setup()
是组件的逻辑入口- 模板中可以自动解包
ref
的值,JS 中则要写.value