There are multiple ways to define the template of VueJS Component. In the last lesson 'Introduction to Component's, we defined in the template of the component as a string.

Even though the approach is good and keeps all the parts of the components at a single place, At times you might have a large HTML template that might be difficult to maintain inside the Component options object.

Using X-Template

In this tutorial let's consider another way to defining templates i.e. X-Template. So instead of keeping our template in the javascript. We can add another element in our HTML and set its type to text/x-template, We also need to give it an id so that we can reference it. You can name the id anything that you would like.

Let's consider the example in our Introduction to Components Tutorial.

<script type="text/x-template" id="button-click-counter-template">
    <button class="btn btn-primary" @click="count++">{{count}}</button>
</script>

We have moved the template string from the Component options object to HTML inside the script tag. And we can now reference it in our Vue Component using the CSS selector.

    Vue.component('button-click-counter',{
        template : '#button-click-counter-template',

        data() {
            return {
                count: 0,
            }
        } 
    });

One drawback of this approach is that we don't get the whole picture of our Component looking at the component's code, we have to look into the HTML to check the template structure.

Comments