Vue JS 2 Basic Components and template: Tutorial 4

By | August 23, 2021

Hello, Coders!! This article tutorial is about the Vue JS 2 Basic Components and template: Tutorial 4. Here we will learn to make components and templates. Components are reusable vue instances.

In the templates, I will pass the HTML tags and render them on the frontend with manipulated data.

Here is the full code for Basic Components:

Index.html

<!DOCTYPE HTML>

<html>
	
	<head>

			<title></title>

	</head>

	<body>

		<div id="root">

			<task>Task 1</task>

			<task>Task 2</task>

			<task>Task 3</task>

			<task>Task 4</task>

			<task>Task 5</task>

		</div>

		

		<script src="https://unpkg.com/vue@2.1.3/dist/vue.js"></script>

		<script src="vue-comonents/main.js"></script>

	</body>
</html>

main.js

Vue.component('task',{

	template: '<li><slot></slot></li>'

});

new Vue({

	el: '#root'

})

Code Explanation:

In the above code, you can see that I have created the js file separately not following the previous tutorial standards to write the js code in the same file. This practice to make the js file separate will be more clear and easy to understand by the developer.

<script src="vue-comonents/main.js"></script>

Now, the components I used in the index.html file can be reusable instances across root div.

<task>Task 1</task>

This task component I have declared inside the root div that I bind with the Vue instance.

Vue.component('task',{

	template: '<li><slot></slot></li>'

});

Here you can see I created a template where I can write the properties with data. but here I wrote the html tag <li> that will make a list at the front. In between, I can directly write the value but I want to take a value from <task></task> input and print it.

So for that, I used <slot>. Whatever I write inside the tag <task> will populate here and bind with an element.

In the above code, you can also see that I used the multiples of the <task>. So that is the reusability of the components. Since components are reusable Vue instances, they accept the same options, such as data, computed, watch, methods, and lifecycle hooks

Output:

vue-component output
vue-component output

You are done here so this article tutorial is about the Vue JS 2 Basic Components and template: Tutorial 4. Keep learning from the vue js 2 series tutorial. You can also check the previous tutorial from the series here Vue JS 2 computed properties: Tutorial 3 Good Luck!

Category: PHP

About Pringal Gigaiya

Full-stack Web Developer & Freelancer Work with PHP MVC Frameworks like Laravel, CodeIgniter, Yii and also work with Python, Vue JS, Flutter.

Leave a Reply

Your email address will not be published. Required fields are marked *