4

I'm going through the official documentation of Vue.js and found this diagram about different stages and steps in a Vue instance's lifecycle. I understand the basic features of Vue but I am unable to understand the meaning of many stages mentioned in the diagram. For example, "Compile template into render function" or "Virtual DOM re-render and patch". I have no idea what they mean.

I know it says in the documentation that you don’t need to fully understand everything right now, but I was hoping if some Vue(or frontend) expert could briefly explain these steps in simple language.

1 Answer 1

4

It can all be a little overwhelming, here's what those things are

Render Functions

When Vue compiles your Vue instance, it creates a render function, which is a pure JavaScript representation of your HTML. Something like this:

new Vue({
  template: `<div>{{msg}}</div>`,
  data:{
    msg: 'Hello Vue
  }
}).$mount('#app')

Will actually turn into something like this:

new Vue({
  render: function(createElement) {
    return createElement('div', this.msg)
  },
  data: {
    msg: 'Hello Vue'
  }
}).$mount('#app')

Here's a JSFiddle: https://jsfiddle.net/bvvbmpLo/

You don't need to handle that, Vue does it for you, and most of the time you won't find yourself writing render functions. However, it is important to understand that Vue is doing some behind the scenes work to represent your templates in pure JavaScript.

Virtual DOM re-render and patch

You really don't need to know about this, but Vue uses a virtual DOM, because it's is easier to track changes and decide which parts of the DOM need updating.

In reality, what happens is that Vue builds up a tree that represents the DOM (called a vTree), then when you change state it uses something called a diffing algorithm which compares the previous vTree to the current vTree as it now stands, and attempts to figure out which part of the page it needs to change to reflect that state in your view. The changing of a small part of your page to represent the new state is called patching.

That's a pretty high-level overview of a virtual DOM, it's fiendishly complex to get this working efficiently which is why frameworks like Vue exist in the first place. If you're interested in learning more about that then try taking a look at Matt-Esch/virtual-dom on Github, which does a great job of explaining this concept in more detail.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is helpful! Could you please include some explanation about one more step of the lifecycle - “Create vm.$el and replace el with it”.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.