Trung BìnhVue.js iconVue.js

Ref unwrapping trong templates và reactive objects hoạt động thế nào?

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!

Xem toàn bộ Vue.js cùng filter theo level & chủ đề con.

Mở danh sách Vue.js