How does v-if work internally?

Asked

Viewed 132 times

5

From what I’ve seen, using the v-if it is possible to show and hide an element through a condition, but it does not function as a toggle of Jquery, the v-if ends up removing the element and can return the same element depending on the condition.

I imagine it’s something like cloning an element, using the .remove() and then a .append() of the original element.

How is this done? What would it be like to do the same thing with pure js or jquery?

  • The v-if is something conditional?

  • is a directive of Vue.js, I wanted to understand the inner workings of it :P

1 answer

4


Vue.js uses the Virtual DOM approach. This method implies first changing in memory, making the diff of what is going to be changed on the screen, and only then changing the DOM. This technique has on average 95~96% efficiency in terms of performance.

v-if removes the DOM node, it would be a normal javascript remove. Code snippet of Vue.js where the removeChild call is executed and just below, the statement of the removeChild function that uses the native javascript resource:

  addClass(clone, moveClass);
  clone.style.display = 'none';
  this.$el.appendChild(clone);
  var info = getTransitionInfo(clone);
  this.$el.removeChild(clone);
  return (this._hasMove = info.hasTransform)

Functions that use native javascript resources:

/*...*/
function removeChild (node, child) {
  node.removeChild(child);
}

function appendChild (node, child) {
  node.appendChild(child);
}
/*...*/

In addition to v-if, we also have v-show. This one works like jQuery’s toggle. The v-show only changes the value from "display" to None. For performance requirements, it is worth using the v-show, but depending on the cases, you can use a v-if. Example where there can be a lot of processing cost in a matter of v-if and v-show, would be a rendering of a table with 1000 items. With the v-show would be much lighter, but in normal situations, the performance between them is virtually equal.

An important detail, if you have a Component inside a v-if, every time there is a change of state from hidden to visible, the Component is again instilled. With the v-show the Component does not change the state, being loaded only once.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.