vue3.x 响应式数据-ref()方式-对象类型 作者:马育民 • 2025-06-08 09:49 • 阅读:10037 # 使用 ### 需要导入 ``` import {ref} from 'vue' ``` ### 定义语法 如果某个对象 **需要 定义为响应式**,就用下面写法 ``` let xxx = ref({ }) ``` **返回值:**`RefImpl`的实例对象,简称`ref对象`,`ref`对象的 `value`**属性是响应式的** ### 插值表达式 还是像之前的写法,没变化 ``` {{xxx.属性}} ``` ### 修改值 通过 `ref` 对象的 `value.属性` 改变 ``` xxx.value.属性 = '新值' ``` # 例子 ``` <template> 姓名:{{student.name}}<br> 年龄:{{student.age}}<br> 性别:{{student.sex}}<br> 身高:{{student.height}}<br> <button @click="addAge">年龄加1</button> <button @click="addHeight">身高加0.01</button> </template> <script lang="ts" setup name='Student'> import {ref} from 'vue' let student = ref({ name:'李雷', age:20, sex:'男', height:1.82 }) console.log("student:",student) function addAge(){ student.value.age++ } function addHeight(){ // height = ref(1.9) student.value.height= 1.9 } </script> <style> </style> ``` ### ref响应对象 访问页面,显示如下: [](https://www.malaoshi.top/upload/0/0/1GW1GuYRmYHk.png) `value` 是 `Proxy` 响应对象 ### 插值表达式 插值表达式就写 `{{student.name}}` 即可 不能写 `{{student.value.name}}`,否则不显示数据 ### 修改值不能再次定义 ref() 修改值时,不能再次定义 `ref()`,如下,页面不会更新数据: ``` function addHeight() { student = ref({ height : 1.9 }) } ``` 原文出处:/show_1GW1GugK1EMC.html