Vue.js templates and interpolations

Here, we will learn about templates and interpolation in Vue.JS

Vue.js uses templating language that is a superset of HTML. Any HTML is a valid Vue.js template and Vue.js provides two powerful things: interpolation and directives.

Examples of Valid HTML Templates:

<span>Hello!</span>

This can be put inside the Vue component also inside the template tag

new Vue({
  template: '<span>Hello!</span>'
})

or it can be put in single file component also.

<template>
  <span>Hello!</span>
</template>

Now, we will see how the interpolation works in Vue.js

new Vue({
  data: {
    name: 'World'
  },
  template: '<span>Hello!</span>'
})

and now to use the interpolation in Vue, we will do this below.

new Vue({
  data: {
    name: 'World'
  },
  template: '<span>Hello {{name}}!</span>'
})

One main thing here is, we don’t need to use this keyword when we use it in templates, as Vue.js does his internal binding and let us use the variable directly without this keyword.

In the Single file component, we can do it like below:

<template>
  <span>Hello {{name}}!</span>
</template>

<script>
export default {
  data() {
    return {
      name: 'World'
    }
  }
}
</script>

We need to use regular functions in data and arrow functions are not possible.

This is because in data we might need to access a method in our component instance, and we can’t do that if this is not bound to the component, so arrow function usage is not possible.

You can use any JavaScript expression inside your interpolations, but you’re limited to just one expression

Like:

{{ name.reverse() }}

OR

{{ name === 'Hello' ? 'Hie' : 'Hyy' }}

The value included in any interpolation will be updated upon a change of any of the data properties it depends on.

If you need to have an HTML snippet you need to use the v-html directive instead.

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories