Vue.js Templates

Vue.js templates are an essential feature that allows developers to create dynamic and reactive user interfaces. They provide a clear and declarative syntax for binding the Vue instance's data to the HTML. In this topic, we will cover everything you need to know about Vue.js templates, from the basics to advanced concepts, with detailed examples and explanations.

What is a Vue.js Template?

A Vue.js template is a special type of HTML that allows you to declaratively bind the DOM to the Vue instance’s data. Templates are at the heart of a Vue component and provide a way to build complex user interfaces efficiently.

Vue.js Templates

Basic Syntax and Directives

Interpolations

Interpolations are the most basic form of binding in Vue.js. They are used to display data directly in the HTML.

				
					<div id="app">
  {{ message }}
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue!'}})</script> 
				
			

Explanation:

  • {{ message }} is a mustache syntax that binds the message data property to the HTML.
  • The output will be
				
					<div id="app">
  Hello Vue!
</div>

				
			

Directives

Directives are special tokens in the markup that tell the library to do something to a DOM element. They have a special v- prefix to indicate that they are special attributes provided by Vue.js template.

v-bind

The v-bind directive dynamically binds one or more attributes, or a component prop, to an expression.

				
					<div id="app">
  <a v-bind:href="url">Visit Vue.js</a>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{url:'https://vuejs.org'}})</script> 
				
			

Explanation:

  • v-bind:href="url" binds the href attribute to the url data property.
  • The output will be a clickable link directing to https://vuejs.org.

v-if

The v-if directive is used for conditional rendering. The element is only rendered if the expression evaluates to true.

				
					<div id="app">
  <p v-if="seen">Now you see me</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{seen:!0}})</script> 
				
			

Explanation:

  • v-if="seen" renders the paragraph only if seen is true.
  • The output will be
				
					<p>Now you see me</p>

				
			

v-for

The v-for directive is used to render a list of items by iterating over an array.

				
					<div id="app">
  <ul>
    <li v-for="item in items">{{ item.text }}</li>
  </ul>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{items:[{text:'Learn JavaScript'},{text:'Learn Vue'},{text:'Build something awesome'}]}})</script> 
				
			

Explanation:

  • v-for="item in items" iterates over the items array.
  • Each item.text is rendered as a list item.
  • The output will be
				
					<ul>
  <li>Learn JavaScript</li>
  <li>Learn Vue</li>
  <li>Build something awesome</li>
</ul>

				
			

v-show

The v-show directive toggles the visibility of an element.

				
					<div id="app">
  <p v-show="isVisible">I am visible</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{isVisible:!0}})</script> 
				
			

Explanation:

  • v-show="isVisible" controls the visibility based on isVisible.
  • The paragraph is displayed because isVisible is true.
  • The output will be
				
					<p>I am visible</p>

				
			

v-model

The v-model directive creates a two-way binding on form input elements.

				
					<div id="app">
  <input v-model="message">
  <p>{{ message }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue!'}})</script> 
				
			

Explanation:

  • v-model="message" binds the input value to the message data property.
  • As you type in the input field, the paragraph updates in real-time.
  • The output will be
				
					<input value="Hello Vue!">
<p>Hello Vue!</p>

				
			

v-on

The v-on directive is used to listen to DOM events.

				
					<div id="app">
  <button v-on:click="greet">Greet</button>
</div> <script type="litespeed/javascript">new Vue({el:'#app',methods:{greet:function(){alert('Hello Vue!')}}})</script> 
				
			

Explanation:

  • v-on:click="greet" listens for the click event and calls the greet method.
  • Clicking the button shows an alert saying “Hello Vue!”.
  • The output will be
				
					<button>Greet</button>

				
			

Template Syntax

Text Interpolation

Text interpolation is used to bind data to the DOM in a straightforward manner.

				
					<div id="app">
  {{ message }}
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue!'}})</script> 
				
			

Explanation:

  • The double curly braces {{ message }} are used for text interpolation.
  • The output will be
				
					<div id="app">
  Hello Vue!
</div>

				
			

Attribute Binding

Attributes can be dynamically bound using the v-bind directive.

				
					<div id="app">
  <a v-bind:href="url">Vue.js Documentation</a>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{url:'https://vuejs.org/v2/guide/'}})</script> 
				
			

Explanation:

  • v-bind:href="url" binds the href attribute to the url data property.
  • The output will be
				
					<a href="https://vuejs.org/v2/guide/" target="_blank" rel="noopener">Vue.js Documentation</a>

				
			

Conditional Rendering

v-if, v-else-if, v-else

These directives control the conditional rendering of elements.

				
					<div id="app">
  <p v-if="type === 'A'">Type A</p>
  <p v-else-if="type === 'B'">Type B</p>
  <p v-else>Other Type</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{type:'A'}})</script> 
				
			

Explanation:

  • v-if, v-else-if, and v-else control which paragraph is rendered based on the type data property.
  • The output will be
				
					<p>Type A</p>

				
			

v-show

The v-show directive toggles the visibility of an element without removing it from the DOM.

				
					<div id="app">
  <p v-show="isVisible">I am visible</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{isVisible:!0}})</script> 
				
			

Explanation:

  • v-show="isVisible" controls the visibility of the paragraph.
  • The output will be
				
					<p style="display: block;">I am visible</p>

				
			

List Rendering

v-for

The v-for directive is used to render lists of items by iterating over arrays or objects.

				
					<div id="app">
  <ul>
    <li v-for="item in items" :key="item.id">{{ item.text }}</li>
  </ul>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{items:[{id:1,text:'Learn JavaScript'},{id:2,text:'Learn Vue'},{id:3,text:'Build something awesome'}]}})</script> 
				
			

Explanation:

  • v-for="item in items" iterates over the items array.
  • :key="item.id" is used to track each item’s identity.
  • The output will be
				
					<ul>
  <li>Learn JavaScript</li>
  <li>Learn Vue</li>
  <li>Build something awesome</li>
</ul>

				
			

Event Handling

v-on

The v-on directive is used to listen to DOM events.

				
					<div id="app">
  <button v-on:click="greet">Greet</button>
</div> <script type="litespeed/javascript">new Vue({el:'#app',methods:{greet:function(){alert('Hello Vue!')}}})</script> 
				
			

Explanation:

  • v-on:click="greet" listens for the click event and calls the greet method.
  • The output will be
				
					<button>Greet</button>

				
			

Event Modifiers

Event modifiers are used to handle common event-related tasks like stopping propagation and preventing default behavior.

				
					<div id="app">
  <button v-on:click.stop="greet">Greet</button>
  <form v-on:submit.prevent="onSubmit">
    <button type="submit">Submit</button>
  </form>
</div> <script type="litespeed/javascript">new Vue({el:'#app',methods:{greet:function(){alert('Hello Vue!')},onSubmit:function(){alert('Form submitted')}}})</script> 
				
			

Explanation:

  • v-on:click.stop="greet" stops the click event from propagating.
  • v-on:submit.prevent="onSubmit" prevents the form from submitting.
  • The output will be buttons that trigger alerts without propagating or submitting.

Form Input Bindings

v-model

The v-model directive creates a two-way binding on form input elements.

				
					<div id="app">
  <input v-model="message">
  <p>{{ message }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue!'}})</script> 
				
			

Explanation:

  • v-model="message" binds the input value to the message data property.
  • The paragraph updates in real-time as you type.
  • The output will be:
				
					<input value="Hello Vue!">
<p>Hello Vue!</p>

				
			

Modifiers for v-model

Modifiers allow fine-tuning of v-model behavior.

				
					<div id="app">
  <input v-model.trim="message">
  <p>{{ message }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:''}})</script> 
				
			

Explanation:

  • v-model.trim="message" trims the input value.
  • The output will be a trimmed input displayed in real-time

Computed Properties and Watchers

Computed Properties

Computed properties are cached based on their dependencies and only re-evaluate when those dependencies change.

				
					<div id="app">
  <p>Reversed Message: {{ reversedMessage }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue!'},computed:{reversedMessage:function(){return this.message.split('').reverse().join('')}}})</script> 
				
			

Explanation

  • reversedMessage is a computed property that returns the reversed message.
  • The output will be
				
					<p>Reversed Message: !euV olleH</p>

				
			

Watchers

Watchers are used to perform asynchronous or expensive operations in response to changing data.

				
					<div id="app">
  <input v-model="question">
  <p>{{ answer }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{question:'',answer:'I cannot give you an answer until you ask a question!'},watch:{question:function(newQuestion){this.answer='Waiting for you to stop typing...';this.getAnswer()}},methods:{getAnswer:_.debounce(function(){if(this.question.indexOf('?')===-1){this.answer='Questions usually contain a question mark. ;-)';return}
this.answer='Thinking...';var vm=this;axios.get('https://yesno.wtf/api').then(function(response){vm.answer=_.capitalize(response.data.answer)}).catch(function(error){vm.answer='Error! Could not reach the API. '+error})},500)}})</script> 
				
			

Explanation:

  • watch watches the question property for changes.
  • _.debounce from lodash is used to limit the rate at which getAnswer is invoked.
  • The output will update the answer after a delay when the question contains a question mark.

Components in Vue.js Templates

Creating Components

Components are reusable Vue instances with a name in Vue.js Template.

				
					<div id="app">
  <todo-item></todo-item>
</div> <script type="litespeed/javascript">Vue.component('todo-item',{template:'<li>This is a todo</li>'});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • Vue.component registers a global component.
  • todo-item is a reusable component.
  • The output will be
				
					<li>This is a todo</li>

				
			

Passing Props

Props are custom attributes you can register on a component. They are passed to the component and can be used for dynamic rendering.

				
					<div id="app">
  <todo-item v-bind:todo="todo"></todo-item>
</div> <script type="litespeed/javascript">Vue.component('todo-item',{props:['todo'],template:'<li>{{ todo.text }}</li>'});new Vue({el:'#app',data:{todo:{text:'Learn Vue'}}})</script> 
				
			

Explanation:

  • props: ['todo'] declares the todo prop.
  • The output will be
				
					<li>Learn Vue</li>

				
			

Emitting Events

Components can emit custom events to communicate with parent instances in Vue.js Instance.

				
					<div id="app">
  <button-counter></button-counter>
</div> <script type="litespeed/javascript">Vue.component('button-counter',{data:function(){return{count:0}},template:'<button v-on:click="count++">{{ count }}</button>'});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • v-on:click="count++" increments the count data property.
  • The output will be a button displaying the current count, which increases on click.

Slots and Scoped Slots

Basic Slots

Slots allow you to compose components like you would normally compose HTML elements.

				
					<div id="app">
  <alert-box>
    <span>This is a message</span>
  </alert-box>
</div> <script type="litespeed/javascript">Vue.component('alert-box',{template:'<div class="alert"><slot></slot></div>'});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • <slot></slot> acts as a placeholder for content passed to the component.
  • The output will be
				
					<div class="alert">
  <span>This is a message</span>
</div>

				
			

Scoped Slots

Scoped slots allow a child component to pass data back to the parent.

				
					<div id="app">
  <my-component>
    <template v-slot:default="slotProps">
      {{ slotProps.text }}
    </template>
  </my-component>
</div> <script type="litespeed/javascript">Vue.component('my-component',{data:function(){return{text:'Hello from the slot'}},template:'<div><slot :text="text"></slot></div>'});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • <slot :text="text"></slot> passes text to the slot.
  • v-slot:default="slotProps" binds slotProps to the slot’s data.
  • The output will be
				
					<div>Hello from the slot</div>

				
			

Here we have covered a comprehensive range of topics related to Vue.js templates, from basic syntax and directives to more advanced concepts like scoped slots and component communication. Vue.js templates offer a powerful and flexible way to bind data to the DOM, enabling you to build dynamic and reactive web applications efficiently.Happy coding !❤️

Table of Contents