背景
ref(),reactive() ???每次记不住该用什么比较合适?
为此整理一个 Vue3 响应式数据最佳实践速查表,涵盖基础值、对象、数组、表单这几类常见场景。
📌 Vue3 响应式数据定义速查表
1. 基础值(string / number / boolean)
👉 推荐用 ref
csharp
import { ref } from 'vue'
const count = ref(0)
const title = ref('Hello Vue3')
const isVisible = ref(true)
✅ 场景:计数器、开关、单一状态。
2. 对象(结构化数据)
👉 推荐用 reactive
php
import { reactive } from 'vue'
const user = reactive({
id: 1,
name: 'Tom',
age: 20
})
user.name = 'Jerry' // 直接修改即可
✅ 场景:用户信息、复杂状态对象。
⚠️ 注意:不能整体替换 user = { ... }
,只能改属性。
👉 如果需要整体替换 → 用 ref({})
更合适。
3. 数组(列表数据)
👉 推荐用 ref([])
csharp
import { ref } from 'vue'
const users = ref<{ id: number; name: string }[]>([])
// 整体替换
users.value = [{ id: 1, name: 'Tom' }]
// 修改内容
users.value.push({ id: 2, name: 'Jerry' })
✅ 场景:表格、分页、查询结果(经常整体替换)。
👉 如果只修改,不会整体替换:
c
const tags = reactive<string[]>(['vue', 'react'])
tags.push('angular')
4. 表单数据
👉 推荐用 reactive
+ toRefs
,方便解构使用
php
import { reactive, toRefs } from 'vue'
const form = reactive({
username: '',
password: '',
remember: false
})
const { username, password, remember } = toRefs(form)
✅ 场景:登录表单、注册表单、复杂输入表单。
👉 如果表单需要 整体重置,可以这样:
php
Object.assign(form, { username: '', password: '', remember: false })
5. DOM 引用
👉 必须用 ref
xml
<template>
<input ref="inputEl" />
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const inputEl = ref<HTMLInputElement | null>(null)
onMounted(() => {
inputEl.value?.focus()
})
</script>
✅ 总结口诀
- 单值用
ref
- 对象用
reactive
(要整体替换就改成ref({})
) - 数组推荐
ref([])
(便于整体替换) - 表单用
reactive + toRefs
- DOM 元素用
ref