vue3.x 响应式数据-reactive()方式-只适用对象类型 作者:马育民 • 2025-06-08 10:36 • 阅读:10038 # 介绍 reactive()方式,只使用对象类型,不能用于基本数据类型 ### 优点 适合深层的对象类型,如下: ``` let student = { hobby:[ { id:1, name:'吃鸡' } ] } ``` # 用法 ### 导入 ``` import { reactive } from 'vue' ``` ### 定义语法 如果某个对象 **需要 定义为响应式**,就用下面写法 ``` let xxx = reactive({ }) ``` **返回值:**`Proxy`的 **响应对象** ### 插值表达式 还是像之前的写法,没变化 ``` {{xxx.属性}} ``` ### 修改值 通过 `ref` 对象的 `xxx.属性` 改变 ``` xxx.属性 = '新值' ``` # 例子 ``` <template> 姓名:{{student.name}}<br> 年龄:{{student.age}}<br> 性别:{{student.sex}}<br> 身高:{{student.height}}<br> <button @click="addAge">年龄加1</button> <button @click="modifyName">修改名字</button> </template> <script lang="ts" setup name='Student'> import { reactive } from 'vue' let student = reactive({ name: '李雷', age: 20, sex: '男', height: 1.82 }) console.log("student:", student) function addAge() { student.age++ } function modifyName() { student.name = '李大雷' } </script> <style> </style> ``` ### Proxy 响应对象 访问页面,显示如下: [](https://www.malaoshi.top/upload/0/0/1GW1GvIJgdq1.png) `student` 是 `Proxy` 对象 # 将一个对象的值赋给该响应对象 将一个对象的各个属性值,如下: ``` let lucy = { name: 'lucy', age: 22, sex: '男', height: 1.62 } ``` 赋值给该响应对象 ### 添加按钮 ``` <button @click="modify">将一个对象的值赋给该响应对象</button> ``` ### 不能再次定义 reactive() 修改值不能再次定义 `reactive()`,否则不能更新页面 ``` function modify(){ let lucy = { name: 'lucy', age: 22, sex: '男', height: 1.62 } student = reactive(lucy) } ``` ### 通过 Object.assign() 修改 关于 `Object.assign()` 详见: https://www.malaoshi.top/show_1GW1GvelRaf8.html ``` function modify() { let lucy = { name: 'lucy', age: 22, sex: '女', height: 1.62 } // student = reactive(lucy) Object.assign(student,lucy) } ``` 原文出处:/show_1GW1GvSWRsSY.html