背景

ref(),reactive() ???每次记不住该用什么比较合适?


Vue3 响应式数据定义速查表

1. 基础值(string / number / boolean)

推荐用 ref

import { ref } from 'vue'

const count = ref(0)
const title = ref('Hello Vue3')
const isVisible = ref(true)

场景:计数器、开关、单一状态。


2. 对象(结构化数据)

推荐用 reactive

import { reactive } from 'vue'

const user = reactive({
  id: 1,
  name: 'Tom',
  age: 20
})

user.name = 'Jerry'   // 直接修改即可

场景:用户信息、复杂状态对象。
️ 注意:不能整体替换 user = { ... },只能改属性。
如果需要整体替换 → 用 ref({}) 更合适。


3. 数组(列表数据)

推荐用 ref([])

import { ref } from 'vue'

const users = ref<{ id: number; name: string }[]>([])

// 整体替换
users.value = [{ id: 1, name: 'Tom' }]

// 修改内容
users.value.push({ id: 2, name: 'Jerry' })

场景:表格、分页、查询结果(经常整体替换)。

如果只修改,不会整体替换:

const tags = reactive<string[]>(['vue', 'react'])
tags.push('angular')

4. 表单数据

推荐用 reactive + toRefs,方便解构使用

import { reactive, toRefs } from 'vue'

const form = reactive({
  username: '',
  password: '',
  remember: false
})

const { username, password, remember } = toRefs(form)

场景:登录表单、注册表单、复杂输入表单。
如果表单需要 整体重置,可以这样:

Object.assign(form, { username: '', password: '', remember: false })

5. DOM 引用

必须用 ref

<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

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]