Updated April 15, 2023
Introduction to Vue.js components
Vue.js components are used for abstraction, which allows for building large-scale applications composing of small and reusable components. Components in Vue.js helps to extend basic HTML elements to encapsulate reusable code. In some cases, components may also appear as native HTML elements extended with the ‘is’ attribute. Covering all the keywords, Vue Component is a reusable, self-contained piece of UI logic; hence Vue.js is also called as ‘Component Framework’. It is a structured way of front-end development that will not spoil the UI development experience and look and feel to end-users.
Syntax
First, we need to create a component constructor.
vue.extend();
var sample_component = Vue.extend({
//component options
} );
For using the above-created constructor as a component, we need to globally register the component with the tag sample_component.
vue.component(tag, constructor):
With out created constructor, the above line will look as below:
vue.component('sample_component', MyComponent);
Once the constructor is registered as a component, the ‘sample_component’ can now be used in parent instance’s as a custom element. These components should be registered before the instantiation of root Vue.
Examples of Vue.js components
Different examples are mentioned below:
Example #1
Code:
import Vue from "vue";
import App from "./Hello";
Vue.config.productionTip = false;
new Vue({
el: "#app",
template: "<App/>",
components: { App }
});
In .vue file:
<template>
<p>{{ text }}, More to come!</p>
</template>
<script>
module.exports = {
data: function() {
return {
text: "Hi This is example on usage of Vue.js Components"
};
}
};
</script>
<style scoped>
p {
font-size: 2.5em;
text-align: center;
}
</style>
Output:
Example #2 – Counter
In js file:
Vue.component('counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
new Vue({ el: '#counter-demo' })
In HTML file:
<div id="counter-demo">
<counter></counter>
</div>
In CSS file:
body {
background: #20262E;
padding: 18px;
font-family: Helvetica;
}
#counter-demo {
background: #fff;
border-radius: 5px;
padding: 18px;
transition: all 0.2s;
}
Output:
On click:
Example #3 – Reusing a Component
In js file:
Vue.component('employee_name', {
props: ['name'],
template: '<p>Hello Mr/Ms {{ name }}</p>'
})
new Vue({
el: "#app"
})
In HTML file:
<div id="app">
<employee_name name="Karthick"></employee_name>
<employee_name name="Saideep"></employee_name>
<employee_name name="Renuka"></employee_name>
<employee_name name="Vikas"></employee_name>
</div>
In CSS file:
body {
background: #20262E;
padding: 18px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 5px;
padding: 18px;
transition: all 0.2s;
}
Output:
Example #4 – Complex Grid Component in Vue.js
Code:
<!DOCTYPE html>
<html>
<head>
<title>Grid Component in Vue.js</title>
<script src="https://unpkg.com/vue"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.educba.com/style.css" />
<script type="text/x-template" id="grid-template">
<table>
<thead>
<tr>
<th v-for="key in columns"
@click="sortBy(key)"
:class="{ active: sortKey == key }">
{{ key | capitalize }}
<span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'">
</span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="entry in filteredHeroes">
<td v-for="key in columns">
{{entry[key]}}
</td>
</tr>
</tbody>
</table>
</script>
</head>
<body>
<!-- root element -->
<div id="demo">
<form id="search">
Search <input name="query" v-model="searchQuery" />
</form>
<demo-grid
:heroes="gridData"
:columns="gridColumns"
:filter-key="searchQuery"
>
</demo-grid>
</div>
<script>
// registering the grid component
Vue.component("demo-grid", {
template: "#grid-template",
props: {
heroes: Array,
columns: Array,
filterKey: String
},
data: function () {
var sortOrders = {};
this.columns.forEach(function (key) {
sortOrders[key] = 1;
});
return {
sortKey: "",
sortOrders: sortOrders
};
},
computed: {
filteredHeroes: function () {
var sortKey = this.sortKey;
var filterKey = this.filterKey && this.filterKey.toLowerCase();
var order = this.sortOrders[sortKey] || 1;
var heroes = this.heroes;
if (filterKey) {
heroes = heroes.filter(function (row) {
return Object.keys(row).some(function (key) {
return String(row[key]).toLowerCase().indexOf(filterKey) > -1;
});
});
}
if (sortKey) {
heroes = heroes.slice().sort(function (a, b) {
a = a[sortKey];
b = b[sortKey];
return (a === b ? 0 : a > b ? 1 : -1) * order;
});
}
return heroes;
}
},
filters: {
capitalize: function (str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
},
methods: {
sortBy: function (key) {
this.sortKey = key;
this.sortOrders[key] = this.sortOrders[key] * -1;
}
}
});
var demo = new Vue({
el: "#demo",
data: {
searchQuery: "",
gridColumns: ["EmployeeName", "Designation"],
gridData: [
{ EmployeeName: "Karthick", Designation: "SSE" },
{ EmployeeName: "Saideep", Designation: "TA" },
{ EmployeeName: "Renuka", Designation: "SE" },
{ EmployeeName: "Vikas", Designation: "GPM" },
{ EmployeeName: "Vyshali", Designation: "DM" }
]
}
});
</script>
</body>
</html>
In style.css:
body {
font-family: Arial, sans-serif;
font-size: 13px;
color: rgb(44, 43, 43);
}
table {
border: 1px dotted #4beea5;
border-radius: 2px;
background-color: rgb(228, 212, 212);
}
th {
background-color: #81b855;
color: rgba(37, 25, 25, 0.66);
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
td {
background-color: #d8a1a1;
}
th,
td {
min-width: 130px;
padding: 12px 22px;
}
th.active {
color: rgb(243, 235, 235);
}
th.active .arrow {
opacity: 2;
}
.arrow {
display: inline-block;
vertical-align: middle;
width: 1;
height: 1;
margin-left: 4px;
opacity: 0.68;
}
.arrow.asc {
border-left: 3px solid transparent;
border-right: 3px solid transparent;
border-bottom: 3px solid rgb(221, 214, 214);
}
.arrow.dsc {
border-left: 3px solid transparent;
border-right: 3px solid transparent;
border-top: 3px solid rgb(255, 240, 240);
}
Output:
We can filter employee names:
With all the examples above, let us see on the building blocks on components.
- ‘el’ used in root components initialized using new Vue( {} ), which identifies DOM element component will mount on.
- ‘props’, will list down all the properties that can be passed down to the child component.
- ‘template’, used to set up a component template which defines the output generated by the component.
- The component also accepts some other properties like ‘data’, local state of the component, ‘method’, ‘computed’, properties associated with the component, and ‘watch’.
Conclusion
With this, we shall conclude our topic ‘Vue.js components’. We have seen what is Vue.js components and have illustrated some of the examples to let you understand better. Syntax of how to create and register constructor as a Vue component is also shown here. Finally, we have seen what are the building blocks which help us in building the Vue components.
Recommended Articles
This is a guide to Vue.js components. Here we discuss the introduction, syntax, and examples of Vue.js components along with code implementation. You may also have a look at the following articles to learn more –