Components in Vue.js

Ranjul Arumadi
Last Updated: May 13, 2022

Introduction

Vue JS is a single-page application framework written in JavaScript (SPAs). Components in Vue.js are Vue objects that can be reused and have custom HTML elements. Components can be reused as many times as desired or used as a child component in another component. We can use data, computed, watch, and methods in a Vue component. Let us look into basic components in Vue.js.

Types of Vue components

There are two ways to define components in Vue.js: locally and globally.

Global components

Components registered globally in the project can be utilized anywhere without a need to export or import the file they're in.

 

We can use the following syntax to construct a global component; it accepts two parameters: the component's name and the object describing its properties.

vue.component('name of component, {properties}')

 

Example:

// Defining component  globally
Vue.component('welcome-note', {
template: '<p> Hello World </p>'
})

// The first Vue instance
new Vue({
el: '#app1'
})

// The second vue instance
new Vue({
el: '#app2'
})

Local components

When a component is built locally, we can only use it where it was made.

 

Example:

// Defining the component
const welcomeNote = {
  // Defining the props
  props: ['name'],
  template: '<h2> Hello {{ name }}</h2>'
};

// Creating a vue instance
new Vue({
  el: '#app',
   // Registering the components locally
  components:{    
   welcomeNote
  }
});

 

The welcome-note component was built locally in the example above by assigning the component object to a variable (component name). It is then registered locally in the Vue instance, which can only be used there.

Props

Components will be useless unless we can supply data to the component, such as the title and content of the particular post we want to display. This is where props can help with it.

 

Props are used to send data down from parent to child components unidirectionally. Custom properties that we can register on a component are known as props. When a value is supplied to a prop attribute on a component instance, it becomes property. The value of that property, like any other component property, is available from within the template.

 

A component can have as many props as it wants, and any value can be supplied to any of them by default. Let’s see an example.
 

App.vue

<template>
 <div>
   <Hello name = "Ram" />
   <Hello name = "Shyam" />
   <Hello name = "Geeta" />
 </div>
</template>

<script>
import Hello from "./Hello.vue"
export default {
 name: "App",
 components: {
   Hello,
 }
};
</script>

 

Hello.vue

<template>
   <h1>Hello {{name}} </h1>
</template>

<script>
export default {
   name: "Hello",
   props: ['name']
};
</script>

 

Output


Note: We must use v-bind to dynamically pass props. This is really useful when we don't know the exact content we're going to render.

Dynamic components

Sometimes, it's useful to dynamically switch between components. It is more efficient to switch between components dynamically without routing. The following is the syntax:

<component v-bind:is=”currentComponent”></component>

 

It is necessary to use the component tag. The is attribute switches the currently selected component.

 

Example:

<template>
 <div id="app">
 <!-- Creating button events to dynamically switch components  -->
 <button @click="selectedComponent = 'GreenCard'">Show Green Card</button>
 <button @click="selectedComponent = 'PurpleCard'">Show Purple Card</button>
 <hr>
 <!-- Binding the current component to the property  -->
 <component :is="selectedComponent"></component>
 </div>
</template>
<script>

 // Importing the components into the app
import PurpleCard from "./PurpleCard.vue";
import GreenCard from "./GreenCard.vue";
export default {
 name: "app",
 components: {
  GreenCard,
  PurpleCard
 },
 data:function(){
   return{
     // Assigning the current component
          selectedComponent: "GreenCard"
   }
 }    
 
};
</script>

 

In the above example, we defined two separate components in the programme. The ': is' bind attribute allows the current component to be dynamically assigned; after that, the button events are used to switch between the two components.

Single file components

It's best to split large web apps with several functionalities into single file components while constructing large web applications. This allows us to combine all of the templates, scripts, and styles into a single.vue file:

 

Example:

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false
// Instantiate the vue instance
new Vue({
 render: h => h(App),
}).$mount('#app')

 

In the above example, the component was defined in a single file in the example above, then imported into the app, which was then rendered to the DOM using the Vue instance.

DOM Template Parsing Caveats

If we write our Vue templates directly in the DOM, Vue will have to retrieve the template string from the DOM. This can lead to some caveats due to the browsers' native HTML parsing behaviour. This is known as DOM template parsing caveats.

Element Placement Restrictions

HTML elements, like <table>, <ol>, <ul>, and <select> have some restrictions on which elements can come inside them. Some elements such as <option>, <li>, and <tr> can only come inside some other elements. This will create issues when using components with elements that have such restrictions. 

 

For example:

<table>
 <row></row>
</table>

 

The custom component <row> will be raised out as invalid content. This will cause errors in the eventually rendered output. We can use the special is an attribute as a workaround.

<table>
 <tr is="vue:row"></tr>
</table>

Case Insensitivity

Attribute names in HTML are case-insensitive. Due to this browsers will interpret any uppercase characters as lowercase. That means when you’re using in-DOM templates, camelCased prop names and event handler parameters need to use their kebab-cased (hyphen-delimited) equivalents:

 

// camelCase in JavaScript
app.component('blog-post', {
 props: ['postTitle'],
 template: `
   <h3>{{ postTitle }}</h3>
 `
})

 

<!-- kebab-case in HTML -->
<blog-post post-title="hello!"></blog-post>

FAQs

  1. What exactly is a Vue component?
    In Vue.js, components are reusable Vue objects with custom HTML elements. We can reuse components indefinitely or be utilised as a child component in another component.
     
  2. What are Vue props?
    Props are used to deliver data in a unidirectional manner from parent to child components. Props are custom properties that you can register on a component. A property is created when a value is passed to a prop attribute on a component instance.
     
  3. What are the two ways to name components?
    The two ways to name components are:
    Kebab case: my-component-name
    Pascal case: MyComponentName
     
  4. What is the use of the $emit method?
    The emit method is used to notify the parent component that something changed.
     
  5. How can parent choose to listen to any event on the child?
    Using v-on or @, the parent can choose to listen to any event on the child component.

Key Takeaways

Some of the most important properties of Components in Vue.js have been discussed. Vue components are reusable Vue objects with configurable HTML elements. We can reuse components an unlimited number of times. Props are used to deliver data in a unidirectional manner from parent to child components. The use of Dynamic and Single File components in Vue.js  is also discussed.

 

Don't stop here. If you liked this blog about Components in Vue.js, check out our Learn Vue free course to learn Vue from scratch. Also, feel free to check out the blog Vue JS Vs. React in 2021.

Was this article helpful ?
2 upvotes