Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Vue's ref perform a DOM lookup each time it is used?

I am currently testing Vue.js, and using a few refs in my project. I am not sure if every time I call a ref in my method, a DOM Lookup is performed, or if vue stores all refs once and then accesses the reference.

I couldn't find an answer on the documentation nor via google.

https://v2.vuejs.org/v2/api/#ref

Example

myDiv = this.$refs.myDiv

Do I need to store the ref in a variable myself or is there no performance impact when calling the ref multiple times?

like image 327
Sirence Avatar asked Dec 24 '22 06:12

Sirence


2 Answers

Going through the source code, when a vue instance is initiated it sets the property $ref = { } to an empty object. See initLifecycle function

This vm.$refs object is populated by checking if the virtual node has ref attribute i.e vnode.data.ref in the registerRef function.

So you do not have to do this yourself.

And referencing $refs.myRef does not perform a DOM lookup. It will be managed by virtual dom patch process.

like image 171
Vamsi Krishna Avatar answered Feb 05 '23 03:02

Vamsi Krishna


does ref perform a DOM lookup each time?

The short answer is No.

Here's my rough understanding: (Please correct me if I am wrong)

Vue uses virtual DOM. In Vue, a virtual representation of a real DOM is VNode. Vue creates a VNode first based on the templates and scripts. After that, Vue compares the virtual DOM (the tree containing all the VNodes) with the real DOM. If there are differences between real and virtual DOM, Vue create the DOM element using document.createElement (or other DOM creating function). document.createElement returns the pointer to the actual DOM element. The pointer is saved into Vnode.elm before the element is appended to the display. Whenever a Vnode is created/updated/destroyed, Vue checks the ref attribute and set this.$refs.refname as Vnode.elm.

In other words, there's never a DOM lookup. Vnode already contains the pointer to the real DOM element. When you use ref, Vue will just assign the existing DOM pointer to the $refs

like image 31
Jacob Goh Avatar answered Feb 05 '23 01:02

Jacob Goh