Vue Components are an important feature of VueJS that creates custom elements, which can be reused in HTML.
Components are created with the Vue.component() method.

- Syntax:
Vue.component('component-name', { options });

It accepts the same options as new Vue(), such as data, computed, watch, methods, and lifecycle hooks. The only exceptions are a few root-specific options like el.
A component's data option must be a function that returns an object, so that each instance can maintain an independent copy of the returned data.

Let's create a component, that will give a better understanding on how components work with Vue.js.
// Define a new component called test_comp
Vue.component('test_comp', {
 data: function(){
 return { txt:'Life is miracle' }
 },
 template: '<div><h4>This is me</h4><p>{{txt}}.</p></div>'
});

To use this Vue component in the html document, create a custom html element where the tag-name is the name of the component (here "test_comp"), then create a Vue instance, like in the following example:
<div id='demo'>
 <test_comp></test_comp>
</div>

<script>
new Vue({ el: '#demo' });
</script>
The custom tag (here <test_comp>) is replaced with the value of the template property from the defined component.

If you have more html tags in component's template, you must wrap the template in a parent element.
In our example we added H4 and P tags inside a Div element.


Reusing Vue Components

Components can be reused as many times as you want.
Example:
<div id='demo'>
 <test_comp></test_comp>
 <test_comp></test_comp>
 <test_comp></test_comp>
</div>

<script>
// Define a new component called test_comp
Vue.component('test_comp', {
 data: function(){
 return { txt:'Life is miracle' }
 },
 template: '<div><h4>This is me</h4><p>{{txt}}.</p></div>'
});

// Create a Vue instance
new Vue({ el: '#demo' });
</script>

Events and Methods in Components

In Vue components we can define methods and event listeners in template.
Example:
<div id='demo'>
Click on these:
 <comp_test></comp_test>
 <comp_test></comp_test>
</div>

<script>
// Define a new component called comp_test
Vue.component('comp_test', {
 template: '<div v-bind:style="styleobj" @click="countClicks">Nr. clicks: {{ nr_c }}.</div>',
 data: function(){
 return {nr_c:0, styleobj:{background:'#babafe', height:'80px', margin:'8px', width:'111px'}};
 },
 methods:{
 countClicks: function(ev){
 this.nr_c++;
 }
 }
});

// Create a Vue instance
new Vue({ el: '#demo'});
</script>

Passing data to Component with Props

In Vue.js props contains variables that are used to pass values to its child components.
Props are custom attributes you can register on a component, and they are defined into an Array in the props property.
Test and study the next example:
<div id='demo'>
 <comp_button text='Comments'></comp_button>
 <comp_button text='Likes'></comp_button>
 <comp_button text='Shares'></comp_button>
</div>

<script>
// Define a new component called comp_button
Vue.component('comp_button', {
 props: ['text'],
 template: '<button>{{text}}</button> '
});

// Create a Vue instance
new Vue({ el: '#demo' });
</script>
Props are almost like named variable, they pass to the child component whatever data they receive from the parent.
We can obtain the same results with the following code (with a v-for directive), which is more elegant:
<div id='demo'>
 <comp_button v-for='txt in ar_txt' v-bind:text='txt'></comp_button>
</div>

<script>
// Define a new component called comp_button
Vue.component('comp_button', {
 props: ['text'],
 template: '<button>{{text}}</button> '
});

const btn_txt =['Comments', 'Likes', 'Shares']; //array with data for text in component

// Create a Vue instance
new Vue({
 el: '#demo',
 data:{
 ar_txt: btn_txt
 }
});
</script>

Global and Local Components

Global components are defined with the Vue.component() method, but the components can also be registered directly in the vue instance, in the components property. This is called Local registration, as shown in the following script:
<div id='demo'>
 <comp_arti v-for='obj in article' v-bind:post='obj'></comp_arti>
</div>

<script>
//array with data for article content in component
const arti =[
 {title: 'Be Happy', cnt:'<i>Just transmit joy</i>'},
 {title: 'Be Good', cnt:'<b>Recognize holiness and innocence in everything you perceive.</b>'},
 {title: 'Be (in) Peace', cnt:'<b>Just be the inner Self.</b>'}
];

// Create a Vue instance
new Vue({
 el: '#demo',
 data:{
 article: arti
 },
 components:{
 comp_arti:{
 props:['post'],
 template:'<div><h3>{{post.title}}</h3><div v-html="post.cnt"></div></div>'
 }
 }
});
</script>

Content Distribution with Slot

If you want to pass html content from parent tag to a component use the custom <slot> tag in component's template.
In the following example, the <slot> tag will be replaced with the HTML content added in the <msg_box> element (parent).
<div id='demo'>
 <msg_box>
 <i>I'm Free.</i>
 </msg_box>
</div>

<script>
Vue.component('msg_box', {
 template:'<div class="my_msg"><b>Success:</b> <slot></slot></div>'
})

// Create a Vue instance
new Vue({
 el: '#demo'
});
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which HTML5 tag defines marked text? (can be used to highlight parts of text)
<mark> <embed> <span>
<p>Free corses: <mark>coursesweb.net</mark> for Web Development.</p>
Which CSS pseudo-class adds a style to an element when the mouse is over it?
:focus :hover :active
a:hover {
  font-weight: bold;
  color: #00da01;
}
Click on the function which returns a string value that represents the number rounded to the x digits after the decimal point.
toPrecision(x) toFixed(x) floor(x)
var num = 12.34567;
num = num.toFixed(2);
alert(num);       // 12.35
Indicate the PHP function which reads an entire file into an array.
[) file() readfile()
$arr = file("a_file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
var_export($arr);
Vue JS Components

Last accessed pages

  1. PHP PDO - Select query, fetch (22273)
  2. Simple arithmetic calculator in PHP (448)
  3. PHP MySQL - using MySQLi (8670)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (62115)
  5. Display UL bullets and OL numbers on the right side (2725)

Popular pages this month

  1. Making DIV Contents Scroll Horizontally, with multiple Div`s inside (1269)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (1241)
  3. Tabs effect with CSS (1226)
  4. Contact page - CoursesWeb (1224)
  5. Insert, Select and Update NULL value in MySQL (729)