in Vue.JS by
Explain about the Composing with Components

1 Answer

0 votes

The component system is another important concept in Vue, because it’s an abstraction that allows us to build large-scale applications composed of small, self-contained, and often reusable components. If we think about it, almost any type of application interface can be abstracted into a tree of components:

In Vue, a component is essentially a Vue instance with pre-defined options. Registering a component in Vue is straightforward:

// Define a new component called todo-item

Vue.component('todo-item', {

  template: '<li>This is a todo</li>'


var app = new Vue(...)Now you can compose it in another component’s template:


  <!-- Create an instance of the todo-item component -->



But this would render the same text for every todo, which is not super interesting. We should be able to pass data from the parent scope into child components. Let’s modify the component definition to make it accept a Prop:-

Vue.component('todo-item', {

  // The todo-item component now accepts a

  // "prop", which is like a custom attribute.

  // This prop is called todo.

  props: ['todo'],

  template: '<li>{{ todo.text }}</li>'


Now we can pass the todo into each repeated component using v-bind:

<div id="app-7">



      Now we provide each todo-item with the todo object

      it's representing, so that its content can be dynamic.

      We also need to provide each component with a "key",

      which will be explained later.



      v-for="item in groceryList"






Vue.component('todo-item', {

  props: ['todo'],

  template: '<li>{{ todo.text }}</li>'



var app7 = new Vue({

  el: '#app-7',

  data: {

    groceryList: [

      { id: 0, text: 'Vegetables' },

      { id: 1, text: 'Cheese' },

      { id: 2, text: 'Whatever else humans are supposed to eat' }






Whatever else humans are supposed to eat

This is a contrived example, but we have managed to separate our app into two smaller units, and the child is reasonably well-decoupled from the parent via the props interface. We can now further improve our <todo-item> component with more complex template and logic without affecting the parent app.

In a large application, it is necessary to divide the whole app into components to make development manageable. but here’s an (imaginary) example of what an app’s template might look like with components:

<div id="app">