Transcript from the "Virtual DOM" Lesson
>> Evan You: So what is a virtual DOM anyway? The actual DOM, most of us know the native DOM API. For example document.createElement, we can create a real div node that represents this div in our actual document. So this is native API. And it's internals are in fact implementing C++ by the browser engine.
[00:00:44] It's just an object.
>> Evan You: So as you can see, the virtual DOM div is just an object. It has a tag that tells us it's a div. It has a data object, which contains possible attributes. If it doesn't have any attributes, it doesn't even need to have a data object. And then it can have a list of children, which is an array of more virtual nodes, so now we have a tree of virtual nodes which constitute the virtual DOM.
[00:02:49] If we, say, use inner HTML to update our app, we're essentially throwing away all the previous DOM nodes, real DOM nodes, regenerating all the real DOM nodes again. So this cost is much much more expensive than, say, just generating a new virtual DOM snapshot. And inner HTML also has a problem.
[00:03:10] It throws away the current state on, say, form input elements and all that stuff. But a common misunderstanding is virtual DOM is what makes a lot of these frameworks fast. It does not. Virtual DOM is just a way to get around the limitations of the original DOM so that it enables this paradigm of declaratively composing what you want the DOM to look like.
[00:03:37] So this unlocks a bunch of possibilities. But there's also this comparison between,
>> Evan You: Well, I'll talk about it later. Another benefit of the virtual DOM is that it decouples rendering logic from the actual DOM, right? So we have the steps of diffing, then we apply those changes to the DOM.
[00:04:04] If we throw away the last step, all of our apps updating logic can actually be executed virtually. It doesn't need to ever touch the DOM. And in fact, if we abstract out these eventual connecting points, API's that touch the DOM and then sort of redirect them to other places.
[00:05:12] So this is the architectural advantage of virtual DOM. Obviously, virtual DOM is not the only way to achieve that, but it's a pretty good way to do that. And render function, finally, it's just a function that returns Virtual DOM. Okay, so templates in VJS are compiling to render functions by the compiler.
[00:05:33] So we have a little app called View Template Explorer, which you can use to sort of get a, you can explore how the templates are compiled into render functions. But we'll talk about what render functions actually look like in more details later.