Vue tự động unwrap refs trong một số contexts — hiểu rõ để tránh bugs:
Template auto-unwrap: refs được auto-unwrap trong template, không cần .value:
vue
<script setup>
const count = ref(0)
const state = reactive({ count: ref(0) })
</script>
<template>
<!-- Tự động unwrap — không cần .value -->
<p>{{ count }}</p>
<p>{{ state.count }}</p>
</template>Reactive object unwrap: ref là property của reactive object được tự động unwrap khi access:
typescript
const count = ref(0)
const state = reactive({ count }) // Wrap ref trong reactive
console.log(state.count) // 0, không phải Ref<0> — auto-unwrap!
state.count++ // Tương đương count.value++
console.log(count.value) // 1 — linked!Không unwrap: ref trong array hoặc Map KHÔNG tự động unwrap:
typescript
const list = reactive([ref(0)])
console.log(list[0].value) // Phải dùng .value!
const map = reactive(new Map([['key', ref(0)]]))
console.log(map.get('key').value) // Phải dùng .value!Vue auto-unwraps refs in certain contexts:
Template auto-unwrap: no .value needed in templates:
vue
<script setup>
const count = ref(0)
</script>
<template>
<p>{{ count }}</p> <!-- Auto-unwrapped -->
</template>Reactive object unwrap: ref as reactive property is auto-unwrapped:
typescript
const count = ref(0)
const state = reactive({ count }) // Wrap
console.log(state.count) // 0, not Ref<0>
state.count++; console.log(count.value) // 1 — linked!No auto-unwrap: refs in arrays or Maps are NOT unwrapped:
typescript
const list = reactive([ref(0)])
console.log(list[0].value) // Must use .value