Vue / 系统课时

ref 与 reactive 选择

ref 与 reactive 选择

ref 和 reactive 都能创建响应式状态,但它们并不是完全等价的写法。真正影响选择的是数据能否被整体替换、是否需要解构,以及团队希望怎样表达状态边界。本节用一个组件建立可直接应用的选择规则。

学习目标

  • 根据值类型和更新方式选择 ref 或 reactive
  • 理解普通解构为什么会丢失 reactive 属性的响应性
  • 在需要整体替换对象时保持响应式引用稳定

先看选择原则

ref 可以保存任意值,脚本中通过 .value 读写;模板会自动解包常见的顶层 ref。它很适合基本类型,也适合“未来可能整体替换”的对象、数组或异步结果。

reactive 只接收对象类型,返回对象代理。它适合一组字段共同组成稳定状态对象,并且日常更新主要发生在属性级别,例如表单、筛选条件或局部编辑状态。

场景 更合适的选择 原因
数字、字符串、布尔值 ref reactive 不能直接包装基本类型
对象可能整体替换 ref 可以安全执行 state.value = nextState
多字段对象长期按属性修改 reactive 访问和修改属性更直接
需要频繁解构单个字段 ref 或 toRefs(reactive()) 普通解构会脱离代理

用一个组件验证差异

下面示例可直接保存为 Vue 3 项目中的 StateChoice.vue。它同时展示基本类型 ref、对象 reactive,以及对响应式对象安全解构的 toRefs。

vue
<script setup lang="ts">
import { computed, reactive, ref, toRefs } from 'vue'

const count = ref(0)

const profile = reactive({
  name: 'Ada',
  role: 'admin'
})

const { name, role } = toRefs(profile)
const label = computed(() => `${name.value} · ${role.value}`)

function increment() {
  count.value += 1
}

function rename() {
  profile.name = 'Grace'
}
</script>

<template>
  <p>Count: {{ count }}</p>
  <p>Profile: {{ label }}</p>
  <button @click="increment">Increment</button>
  <button @click="rename">Rename</button>
</template>

预期结果

text
初始显示:
Count: 0
Profile: Ada · admin

点击 Increment 后:
Count: 1

点击 Rename 后:
Profile: Grace · admin

count 是单值状态,因此 ref 最自然。profile 是一组长期按字段更新的数据,因此 reactive 让代码更简洁;当需要把字段单独拿出来继续使用时,toRefs 保留了它们与原代理之间的响应式连接。

避免直接解构 reactive

下面这种写法会取得当时的普通值,而不是继续追踪 profile 代理上的属性:

ts
import { reactive } from 'vue'

const profile = reactive({ name: 'Ada', role: 'admin' })
const { name } = profile

profile.name = 'Grace'
console.log(name)

预期输出

text
Ada

name 只是解构时得到的字符串。要保留响应性,可以使用 toRefs(profile),或者直接在使用位置读取 profile.name。如果从设计上就需要大量独立字段,也可以从一开始分别使用多个 ref。

整体替换时优先 ref

reactive 的响应性依赖当前代理对象。若业务状态经常被接口结果整体替换,使用 ref 更直接:

ts
import { ref } from 'vue'

type User = {
  id: number
  name: string
}

const user = ref<User>({ id: 1, name: 'Ada' })
user.value = { id: 2, name: 'Grace' }

console.log(user.value.name)

预期输出

text
Grace

这种模式尤其适合详情数据、当前选中项和异步请求结果。相反,如果对象身份长期稳定,只是不断修改 loading、keyword、page 等字段,reactive 往往更顺手。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

ref 与 reactive 选择

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通