vue3中ref自动解包

1.模板中使用 ref 类型的数据,会自动解包,注意需要是顶级的ref

vue3 复制代码
<template>
<!-- 自动解包-->
  <div>{{ name }}</div>
</template>

<script setup>
import { ref} from 'vue'
const name = ref('hello')
</script>

下面的 ref 不会自动解包

vue3 复制代码
<template>
  <div>
    {{ num }} -- {{ obj.id }}
    <br>
   num+1-----------{{ num+1 }} 
   <br>
   obj.id+1-----------{{ obj.id + 1 }} 
  </div>
</template>

<script setup>
import { ref } from 'vue'
const num = ref(0);
const obj = {
  id: ref(1)
}
</script>
复制代码
### 2.ref作为reactvie对象属性,自动解包
```vue3
<template>
  <div>{{obj.name}}</div>
</template>

<script setup>
import { ref, reactive } from 'vue'
const name = ref('hello')
const obj= reactive({
  name
})
console.log(obj.name) // 自动解包hello
</script>

3.ref 作为 shallowReactive 对象的属性,不会自动解包

vue3 复制代码
<template>
<!-- 此处会显示处"hello" ,双引号也是会有的 -->
  <div>{{obj.name}}</div> 
</template>

<script setup>
import { ref, shallowReactive } from 'vue'
const name = ref('hello')
const obj= shallowReactive ({
  name
})
console.log(obj.name) // 不会自动解包,此处会打印出RefImpl 
</script>

4.ref 数据作为 reactvie 数组或者集合的一个元素,不会自动解包

vue3 复制代码
const people= reactive([ref('zhangsan')])
console.log(people[0]) ; // 此处是RefImpl
console.log(people[0].value) ;//zhangsan
相关推荐
DARLING Zero two♡1 分钟前
浏览器里跑 AI 语音转写?Whisper Web + cpolar让本地服务跑遍全网
前端·人工智能·whisper
꒰ঌ小武໒꒱17 分钟前
文件上传全维度知识体系:从基础原理到高级优化
javascript·node.js
Lovely Ruby26 分钟前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·学习·golang
老华带你飞26 分钟前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
JIngJaneIL31 分钟前
基于Java酒店预约系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
深红33 分钟前
玩转小程序AR-实战篇
前端·微信小程序·webvr
银空飞羽34 分钟前
让Trae SOLO全自主学习开发近期爆出的React RCE漏洞靶场并自主利用验证(CVE-2025-55182)
前端·人工智能·安全
钮钴禄·爱因斯晨44 分钟前
DevUI 组件生态与 MateChat 智能应用:企业级前端智能化实战
前端
不会写DN1 小时前
存储管理在开发中有哪些应用?
前端·后端