In Vue, Templates are used to define the structure and layout of a component's HTML markup.
Templates can contain HTML, Vue directives, and moustache syntax for data binding.
They provide a way to declaratively describe the UI of a Vue component and are an essential part of Vue development.
We can define the template directly within the component options using the template property.
This approach is suitable for small components with simple templates.
Vue.component('your-component', { template: ` <div> <h1>Heading 1</h1> <p>This is a Paragraph!</p> </div> `, });
For larger and more complex components, Vue supports Single File Components, which separate the "template", "script", and "style" into separate sections within a single ".vue" file.
<!-- YourComponent.vue --> <template> <div> <h1>{{ message }}</h1> <h1>Heading 1</h1> <p>This is a Paragraph!</p> </div> </template> <script> export default { data() { return { message: 'Hello, Vue!' }; } } </script> <style scoped> /* CSS styles specific to this component */ </style>
<!-- App.vue --> <script setup> import YourComponent from './components/YourComponent.vue' </script> <template> <header> <div class="wrapper"> <YourComponent /> </div> </header> </template>
Ex- in the script tag we are importing Child Component (`YourComponent`) in Parent Component (`App.vue`) and the parent component has its template where we can declare our ChildComponent to be rendered.
In `YourComponent`, Default data we are passing on the `message` attribute within the component. with the help of Interpolation data binding, we are displaying the `message` text.
Note: Single File Components provide better organization, separation of concerns, and tooling support for Vue.js projects.
The "" tag contains the HTML template for the component.
The "
The "
Vue.js templates use a special syntax that allows us to bind data, handle events, conditionally render elements, and iterate over lists.
Interpolation: {{ expression }} for data binding.
Directives: v-bind, v-on, v-if, v-for, etc.
Event handling: @event or v-on:event for event handling.
Conditional rendering: v-if, v-else, v-else-if, v-show.
List rendering: v-for for iterating over arrays.
Templates in Vue.js provide a flexible and intuitive way to build dynamic and interactive user interfaces.
Whether we're using inline templates or Single File Components, Vue.js templates allow us to declaratively define our UI and leverage Vue features such as "data binding", "directives" and "event handling".