r/vuejs•
NaveenCoder

How vue js directives work?

I am a beginner. When I write vue directives like v-bind , v-if in source code HTML it is there. But when I open the web page there is no directives inside the HTML of the page. How does this happens? Where does directives are stored? How does vuejs compilation takes place? I want to understand the magic.

Posted Jun 3, 2019, 1:47 AM UTC

32
AwesomeInPerson•

Vue works with "render functions" internally.

So if you write <p>Hello World</p>, Vue will turn that into something along the lines of:

createElement('p', 'Hello World');

If you use dynamic values in your template, Vue will re-run this function every time a value changes, so <p>Hi, {{ name }}!</p> will turn into

function(props) {
  return createElement('p', ['Hi, ', props.name, '!']);
}

and then Vue will run this function every time the name changes and write the resulting HTML into the DOM – that's the part you see. Same goes for directives like v-if, they're simply turned into the equivalent if statement within the render function.
So Vue will turn

<p v-if="showFirst">The first line!</p>
<p v-else>The second line!</p>

into

function(props) {
  if (props.showFirst) {
    return createElement('p', 'The first line!');
  } else return createElement ('p', 'The second line!');
}

When you write your template in the HTML, Vue will parse it when it starts up and create a render function (or actually not one but a lot of them) from it. After it has done that, it removes the HTML template as it isn't needed anymore, and replaces it with whatever these render functions output.

How exactly Vue compiles the HTML into the functions and how these render functions work is rather advanced knowledge – but the advanced sections of the docs and at some point the source code can help you out.

25
NaveenCoderOP•

Thank you so much for answering!

3