Components with inline templates in Vue.js
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>
<ul>
<li>{{ elementAbout }}</li>
<li>{{ elementContact }}</li>
<li>{{ elementTheme }}</li>
</ul>
</sidebar>
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.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.