Open In App

Vue Templates

Last Updated : 06 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Vue.js is a progressive JavaScript framework for building user interfaces. One of the core features of Vue.js is its templating system, which allows developers to declaratively bind data to the DOM. In this article, we will explore the basics of Vue templates, including syntax, directives, binding, conditional rendering, loops, and best practices.

What are Vue Templates?

Vue templates use an HTML-like syntax within Vue components, enabling developers to bind data to the DOM in a declarative manner. This approach simplifies the management and updating of the view.

Defining Templates within a Vue Instance

In Vue.js, you can specify the HTML structure of a component directly within the Vue instance by using the template option. This approach is particularly useful for simple components where you want to include the HTML template inline.

In this example, the template property of the Vue instance is used to include HTML content. The HTML is enclosed in backticks, allowing you to write multiple lines of HTML. The data function returns an object with a greeting property that is bound to the template, demonstrating how Vue can dynamically update the content displayed.

<div id="app"></div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const app = Vue.createApp({
template: `
<h1>{{ greeting }}</h1>
<p>This paragraph is added using the template configuration option.</p>
`,
data() {
return {
greeting: "Welcome to Vue.js!"
}
}
})
app.mount('#app')
</script>

Single File Components (SFCs)

For larger projects, Single File Components (SFCs) provide a more organized way to manage your Vue components. An SFC combines the template, script, and style into one .vue file, enhancing separation and ease of maintenance.

An SFC generally includes three sections:

  • <template>: Holds the HTML markup.
  • <script>: Contains the JavaScript code.
  • <style>: Defines the CSS styles.

Here’s an example of a simple SFC:

<template>
<div>
<h1>{{ message }}</h1>
<p>This is a second line of HTML code</p>
</div>
</template>

<script>
export default {
data() {
return {
message: "Hello Geeks!"
}
}
}
</script>

<style>
h1 {
color: blue;
}
</style>

Conclusion

Vue templates are a powerful feature that allows developers to build dynamic, data-driven web applications efficiently. By understanding the basics of Vue templates and following best practices, you can create clean and maintainable code.


Next Article

Similar Reads