HTML interpolation within Vue.js

HTML interpolation within Vue.js

Introduction

vue.js

Vue.js is a MVVM framework, which has a system to connect the “model” (data) to the corresponding “view”. The “view” section, like in other frontend libraries, is actually HTML, but with additional functionalities that allow it to display the model dynamically, namely:

  • “interpolation”
  • “directives”

The part of the HTML code over which interpolation is performed is marked with double curly brackets, and such syntax is known as “Mustache syntax”. Anything inside double curly brackets will be processed by Vue.js and replaced with the appropriate result.

Text interpolation

If there is text between the brackets that represents a property from the “data” object, this syntax will display the current value from that property in the HTML frame. Since the “data” property is specific and acts as a proxy to the vue instance, it is not necessary to use the this.data.property syntax, just the name of the property is sufficient. The most important thing about text interpolation is that Vue.js will reprocess everything inside the brackets if the data changes, after which it will automatically update the HTML.

This method interprets “data” as plain text, not HTML. If it is necessary to evaluate HTML, then the directive “v-html” is used. It should be emphasized that text interpolation cannot be used to interpret HTML tag attributes, for that it is necessary to use the “v-bind” directive.

Interpolation of JavaScript expressions

When a JavaScript expression is found between double curly brackets, it will be processed by Vue.js. After processing the expression inside these double braces Vue.js returns something appropriate for the DOM, something that can be converted to a string.

a) Interpolation of a simple expression

A simple JavaScript expression can be found within the double curly braces that Vue.js will process and render its result at that location. The restriction is that there can only be one JavaScript expression per set of curly braces, which means that loops and complicated logic are not possible. So for complicated logic use “methods” or “computed properties”.

Example

b) Interpolation of the “method” property

Mustache syntax can be used to display the result of a method definition, and for this it is enough to call the desired method within double curly brackets:

Vue.js will call the method again every time the page is re-rendered.

c) Interpolation of the “computed” property

If we want to display the results of a “computed” property, then within double curly brackets write only its name (without brackets):