How does VUE engine evaluates attribute code?

Viewed 277

In VUE it is possible to write full JS expressions inside attributes. For example for the <div> below,

var app = new Vue({ el: '#app', data: { message: 'Hello Vue!', num: 3 } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input v-model="message"/>
  <div v-html="'abc' + ' ' + message + ' ' + 2 * num"></div>
</div>

The result is abc HelloVue! 6.


How does VUE calculates this result? Some kind of sandboxed eval?

Where in the VUE's repo does this calculation happen?

1 Answers

The whole template is compiled into a big render function in JavaScript. Attribute and prop bindings are evaluated inline when the vnode for that element is rendered.

This template:

<div v-html="'abc' + ' ' + message + ' ' + 2 * num"></div>

is compiled into something like:

vnode = _c('div', {
  domProps: {
    "innerHTML": _s('abc' + ' ' + message + ' ' + 2 * num)
  }
})

The entire render function is wrapped in a with(this) { ... } statement so that properties on the component instance can be written like message instead of this.message.

There is no eval() happening, it is executed directly as if you had written the render function by hand. The template compiler code may use new Function() at compile time to check that the syntax is valid, but during execution of the app no such sandboxing is performed.

This online Vue 2 template compiler shows how templates are compiled into render functions.

Vue 3 compiles templates differently and is more optimized. Use Vue Template Explorer to experiment with it.

Related