How does v-if work internally?

5

From what I saw, using v-if you can show and hide an element through a condition, but it does not work as a toggle Jquery, strong> v-if ends up removing the element and is able to return the same element depending on the condition.

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

How is this done? How would it be doing the same thing with js pure or jquery?

    
asked by anonymous 30.08.2017 / 02:56

1 answer

4

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

The v-if removes the node from the DOM, it would even be a normal remove from javascript. 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 feature:

  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 features:

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

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

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

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 instantiated again. With v-show the component does not change the state, being loaded only once.

    
30.08.2017 / 19:32