Vue Templates
Template Syntax and Interpolation:
Templates are HTML-based and use a special syntax to bind data and manipulate the DOM.
Interpolation is one of the core features of Vue.js templates and is achieved by wrapping expressions with double curly braces {{}}.
Inside these curly braces, you can include JavaScript expressions, variables, or data properties defined in the Vue instance.
Example:
<div id="app">
<p>{{ message }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
}
});
</script>
In this example, the message data property is interpolated inside the <p> element, resulting in the text "Hello, Vue!" being displayed in the browser.
Conditionals and Loops:
Vue. js has directs for conditional rendering (v-if, v-else-if, v-else) and list rendering (v-for).
Such directives let you to display or hide elements under some conditions and to dynamically generate HTML elements based on data arrays.
Example:
<div id="app">
<p v-if="isLoggedIn">Welcome, {{ username }}!</p>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
isLoggedIn: true,
username: 'John',
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
}
});
</script>
In this case, the <p> element is displayed or removed depending on the value of isLoggedIn and the <li> elements are created dynamically by using v-for to loop over the items array.
Computed Properties vs. Methods:
Computed properties and methods are both employed to compute and to give dynamic values in Vue.
although they are the same, they have different usage and behavior. Computed properties are stored in cache based on their dependencies, thus, they only re-evaluate when their dependencies have been modified. The methods, in contrast, are called every time they are referenced in the template.
Example:
<div id="app">
<p>Computed: {{ reversedMessage }}</p>
<p>Method: {{ reverseMessage() }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
},
methods: {
reverseMessage() {
return this.message.split('').reverse().join('');
}
}
});
</script>
The original message string is reversed by both reversedMessage and reverseMessage().
But, reversedMessage is a computed property and reverseMessage() is a method.
The computed property will only be re-evaluated when the message changes, while the method will be called as many times as it is referenced in the template.