1

This official Vue.js documentation claims that the ref() API in Vue 3 uses getters and setters.

In Vue 3, Proxies are used for reactive objects and getter / setters are used for refs.

This would imply, according to my understanding, positive identity checks when comparing an object with the value of its reference. The following example seems to prove the contrary.

Is there a gap in my understanding? Is the abovementioned article out-of-date?

const obj = {};
const objRef = Vue.ref(obj);

Vue.createApp({
setup() {
    return {
        answer: obj === objRef.value,
    };
}
}).mount('#app');
<script src="https://unpkg.com/vue@3"></script>

<div id="app">
      <code>obj === objRef.value</code> evaluates to <span>{{ answer }}</span>
</div>

2
  • I think you draw the wrong implication from the documentation. this section of the docs makes it clear that a reactive object (which includes objects created using ref) are not the equal to the original object. Commented Nov 5, 2024 at 14:33
  • 1
    @yoduh I suppose the OP interpreted the statement as if refs don't use proxies, like suggested by the pseudocode in the linked section Commented Nov 5, 2024 at 14:36

1 Answer 1

1

ref creates deeply reactive object with value property:

const objRef = ref(obj);
console.log(obj !== objRef.value); // true
console.log(obj === toRaw(objRef.value)); // true

This means that nested properties like objRef.value.foo.bar are reactive, and nested refs are unwrapped.

If this is not desirable then shallowRef should be used instead:

const objRef = shallowRef(obj);
console.log(obj === objRef.value); // true
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. This would mean that the documentation is actually wrong. Am I wrong?
It's ambiguous. It discusses the simplified implementation in the section you linked vuejs.org/guide/extras/… and not the exact Vue.ref implementation. What they show as function ref(value) is close to shallowRef, no real ref is shown

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.