The Vue documentation states the following:
Unlike reactive objects, there is no unwrapping performed when the
ref
is accessed as an element of areactive array
or a native collection type likeMap
Here are some examples provided in the documentation:
const books = reactive([ref('Vue 3 Guide')])
// need .value here
console.log(books[0].value)
const map = reactive(new Map([['count', ref(0)]]))
// need .value here
console.log(map.get('count').value)
However, the ref
is automatically unwrapped when used inside a reactive
object as shown below:
When a ref is accessed or mutated as a property of a reactive object, it is also automatically unwrapped so it behaves like a normal property
The code snippet demonstrating this behavior is as follows:
const count = ref(0)
const state = reactive({
count
})
console.log(state.count) // 0
state.count = 1
console.log(count.value) // 1
Could someone clarify why this behavior exists? Why is it necessary to use .value
to access values of a ref
element inside a reactive
array?