DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Vue.js Tutorial: Build a Tesla Battery Range Calculator in Vue 3
  • Automated Bug Fixing: From Templates to AI Agents
  • Dynamic File Upload Component in Salesforce LWC
  • Mocking Dependencies and AI Is the Next Frontier in Vue.js Testing

Trending

  • Role of Cloud Architecture in Conversational AI
  • Agentic AI and Generative AI: Revolutionizing Decision Making and Automation
  • Building AI-Driven Intelligent Applications: A Hands-On Development Guide for Integrating GenAI Into Your Applications
  • How to Format Articles for DZone
  1. DZone
  2. Coding
  3. JavaScript
  4. 7 Ways to Define a Component Template in Vue.js

7 Ways to Define a Component Template in Vue.js

Having a hard time deciding on which method to use to define your component template? Read on for some great tips from a Vue.js expert.

By 
Anthony Gore user avatar
Anthony Gore
DZone Core CORE ·
Updated Feb. 10, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
30.9K Views

Join the DZone community and get the full member experience.

Join For Free

There's plenty of choices when it comes to defining component templates in Vue. By my count there are at least seven different ways:

  • String
  • Template literal
  • X-Templates
  • Inline
  • Render functions
  • JSX
  • Single page components

And maybe more!

In this article, we'll go through examples of each and address the pros and cons so you know which one is the best to use in any particular situation.

1. Strings

By default, a template will be defined as a string in your JS file. I think we can all agree that templates in a string are quite incomprehensible. This method doesn't have much going for it other than the wide browser support.

Vue.component('my-checkbox', {
    template: `<div class="checkbox-wrapper" @click="check"><div :class="{ checkbox: true, checked: checked }"></div><div class="title">{{ title }}</div></div>`,
    data() {
        return { checked: false, title: 'Check me' }
    },
    methods: {
        check() { this.checked = !this.checked; }
    }
});

2. Template Literals

ES6 template literals ("backticks") allow you to define your template across multiple lines, something you can't do in a regular JavaScript string. These are much easier to read and are supported now in many new browsers, though you should probably still transpile down to ES5 to be safe.

This method isn't perfect, though; I find that most IDEs still give you grief with syntax highlighting, and formatting the tabs, newlines, etc. can still be a pain.

Vue.component('my-checkbox', {
    template: `<div class="checkbox-wrapper" @click="check">
                            <div :class="{ checkbox: true, checked: checked }"></div>
                            <div class="title">{{ title }}</div>
                        </div>`,
    data() {
        return { checked: false, title: 'Check me' }
    },
    methods: {
        check() { this.checked = !this.checked; }
    }
});

3. X-Templates

With this method, your template is defined inside a script tag in the index.html file. Th script tag is marked with text/x-template and referenced by an id in your component definition.

I like that this method allows you to write your HTML in proper HTML markup, but the downside is that it separates the template from the rest of the component definition.

Vue.component('my-checkbox', {
    template: '#checkbox-template',
    data() {
        return { checked: false, title: 'Check me' }
    },
    methods: {
        check() { this.checked = !this.checked; }
    }
});
<script type="text/x-template" id="checkbox-template">
    <div class="checkbox-wrapper" @click="check">
        <div :class="{ checkbox: true, checked: checked }"></div>
        <div class="title">{{ title }}</div>
    </div>
</script>

4. Inline Templates

By adding the inline-template attribute to a component, you indicate to Vue that the inner content is its template, rather than treating it as distributed content (see slots).

It suffers the same downside as x-templates, but one advantage is that content is in the correct place within the HTML template and so can be rendered upon page load rather than waiting until JavaScript is run.

Vue.component('my-checkbox', {
    data() {
        return { checked: false, title: 'Check me' }
    },
    methods: {
        check() { this.checked = !this.checked; }
    }
});
<my-checkbox inline-template>
    <div class="checkbox-wrapper" @click="check">
        <div :class="{ checkbox: true, checked: checked }"></div>
        <div class="title">{{ title }}</div>
    </div>
</my-checkbox>

5. Render Functions

Render functions require you to define your template as a JavaScript object. They are clearly the most verbose and abstract of the template options.

However, the advantages are that your template is closer to the compiler and gives you access to full JavaScript functionality rather than the subset offered by directives.

Vue.component('my-checkbox', {
    data() {
        return { checked: false, title: 'Check me' }
    },
    methods: {
        check() { this.checked = !this.checked; }
    },
    render(createElement) {
        return createElement(
            'div',
            {
                    attrs: {
                        'class': 'checkbox-wrapper'
                    },
                    on: {
                        click: this.check
                    }
            },
            [
                createElement(
                'div',
                {
                    'class': {
                        checkbox: true,
                        checked: this.checked
                    }
                }
                ),
                createElement(
                'div',
                {
                    attrs: {
                    'class': 'title'
                    }
                },
                [ this.title ]
                )
            ]
        );
    }
});

6. JSX

The most controversial template option in Vue is JSX. Some developers see JSX as ugly, unintuitive, and as a betrayal to the Vue ethos.

JSX requires you to transpile first, as it is not readable by browsers. But, if you need to use render functions, JSX is surely a less abstract way of defining a template.

Vue.component('my-checkbox', {
    data() {
        return { checked: false, title: 'Check me' }
    },
    methods: {
        check() { this.checked = !this.checked; }
    },
    render() {
        return <div class="checkbox-wrapper" onClick={ this.check }>
                 <div class={{ checkbox: true, checked: this.checked }}></div>
                 <div class="title">{ this.title }</div>
               </div>
    }
});

7. Single File Components

So long as you are comfortable with using a build tool in your setup, Single File Components are the king of template options. They bring the best of both worlds: allowing you to write markup while keeping all your component definitions in one file.

They require transpiling and some IDEs don't support syntax highlighting for this file type - but they are otherwise hard to beat.

<template>
  <div class="checkbox-wrapper" @click="check">
    <div :class="{ checkbox: true, checked: checked }"></div>
    <div class="title">{{ title }}</div>
  </div>
</template>
<script>
  export default {
    data() {
      return { checked: false, title: 'Check me' }
    },
    methods: {
      check() { this.checked = !this.checked; }
    }
  }
</script>

You might argue there are even more template definition possibilities since you can use template pre-processors like Pug with SFCs!

Which Is the Best?

Of course, there's no one perfect way, and each should be judged on the use case you have. I think the best developers will be aware of all the possibilities and have each as a tool in their Vue.js toolbelt!

Template Vue.js

Published at DZone with permission of Anthony Gore, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Vue.js Tutorial: Build a Tesla Battery Range Calculator in Vue 3
  • Automated Bug Fixing: From Templates to AI Agents
  • Dynamic File Upload Component in Salesforce LWC
  • Mocking Dependencies and AI Is the Next Frontier in Vue.js Testing

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!