最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does Vue's ref perform a DOM lookup each time it is used? - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 6

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.

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.

发布评论

评论列表(0)

  1. 暂无评论