Components with inline templates in Vue.js

Amit Merchant · May 13, 2020 ·

Vue.js has this handy feature where you can set the inline-template special attribute on the component and now the component can use its inner content as its template, rather than treating it as distributed content.

So, for instance, let’s say I have this component called sidebar, I can attach the inline-template attribute to it like so.

<sidebar inline-template>
        <li>{{ elementAbout }}</li>
        <li>{{ elementContact }}</li>
        <li>{{ elementTheme }}</li>

Now, Vue will treat the content inside the sidebar as its template and you don’t have to give template explicitly using Vue.component. This can be useful when you want to add some amount of reactivity to a little part of the application without adding a lot of complexity.

Although, this is an inline template, the rules for the template are still true here. i.e , You’ve to wrap your entire template into a single root element and that is exactly what I did in this example by wrapping the content in a single root element <ul>.

Now, we can define the component and make it dynamic like so.

Vue.component('sidebar', {
    data() {
        return {
            elementAbout: 'Amit Merchant',
            elementContact: '[email protected]',
            elementTheme: 'Dark'

Here’s the complete example on the CodePen.

See the Pen Vue Inline Template Example by Amit Merchant (@amit_merchant) on CodePen.

Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!