欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > vue3中ref自动解包

vue3中ref自动解包

2025/9/18 13:04:29 来源:https://blog.csdn.net/weixin_44224712/article/details/141679618  浏览:    关键词:vue3中ref自动解包

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

<template>
<!-- 自动解包--><div>{{ name }}</div>
</template><script setup>
import { ref} from 'vue'
const name = ref('hello')
</script>

下面的 ref 不会自动解包

<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 对象的属性,不会自动解包

<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 数组或者集合的一个元素,不会自动解包

const people= reactive([ref('zhangsan')])
console.log(people[0]) ; // 此处是RefImpl
console.log(people[0].value) ;//zhangsan

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词