admin管理员组文章数量:1334342
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.
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?
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/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?
Share Improve this question edited Jul 14, 2022 at 1:24 tony19 139k23 gold badges277 silver badges347 bronze badges asked Jun 14, 2018 at 7:59 RenceRence 2,9503 gold badges26 silver badges44 bronze badges3 Answers
Reset to default 6Going 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.
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 pares 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
The references are registered once and cached in the $refs
object. You can use them directly, no problem.
本文标签: javascriptDoes Vue39s ref perform a DOM lookup each time it is usedStack Overflow
版权声明:本文标题:javascript - Does Vue's ref perform a DOM lookup each time it is used? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742369479a2461942.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论