Vue数据响应式reactive

发布于:2025-09-09 ⋅ 阅读:(19) ⋅ 点赞:(0)

基本作用

在Vue3中,reactive是用来创建响应式对象,reactive接收一个普通的对象,返回一个深层响应式代理对象,所谓"深层",是指对象的嵌套属性(包括数组,对象里的对象)也会被转成响应式的.

import { reactive } from 'vue'
const state = reactive({
  count: 0,
  user: {
    name: '张三',
    age: 18
  }
})

现在,state.countstate.user.name的变化,都会被Vue追踪,并自动触发视图更新

与ref的区别

  • ref适合存储基本类型(数字,字符串,布尔值),取值时需要.value
  • reactive更适合对象/数组,直接点属性即可,不需要.value
    示例对比:
import { ref, reactive } from 'vue'

const num = ref(0)          // 基本类型
num.value++                 // 修改时要用 .value

const obj = reactive({ a: 1 })
obj.a++                     // 直接修改即可

特点

  1. 深层响应式
    不用担心嵌套对象不生效:
   state.user.age++  // 会触发响应式更新
  1. 返回的是代理对象:
    所以不能再用===直接对比原始对象和reactive对象
const raw = { a: 1 }
const state = reactive(raw)
console.log(state === raw) // false
  1. 适合复杂状态管理
    在组件中维护多个字段,深层嵌套时,用reactive更直观

常见用法

  • 在setup里定义组件状态:
  <script setup>
import { reactive } from 'vue'

const state = reactive({
  count: 0,
  todos: []
})

function increment() {
  state.count++
}
</script>
<template>
  <div>
    <p>计数: {{ state.count }}</p>
    <button @click="increment">增加</button>
  </div>
</template>
  • 配合解构(注意要用toRefs否则响应式会丢失)
import { reactive, toRefs } from 'vue'
const state = reactive({ count: 0, msg: 'hi' })
const { count, msg } = toRefs(state)
// 现在 count 和 msg 都是 ref

总结

  • reactive用于对象和数组的响应式转换
  • 配合ref一起用,可以灵活管理不同类型的状态

网站公告

今日签到

点亮在社区的每一天
去签到