Categories

Oct 1, 2019 in Vue.JS

Q: Explain about the Composing with Components

1 Answer

Oct 1, 2019

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:

<ol>

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

  <todo-item></todo-item>

</ol>

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">

  <ol>

    <!--

      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.

    -->

    <todo-item

      v-for="item in groceryList"

      v-bind:todo="item"

      v-bind:key="item.id"

    ></todo-item>

  </ol>

</div>

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' }

    ]

  }

})

Vegetables

Cheese

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">

  <app-nav></app-nav>

  <app-view>

    <app-sidebar></app-sidebar>

    <app-content></app-content>

  </app-view>

</div>

Click here to read more about Vue JS
Click here to read more about Insurance

Related questions

Madanswer
Oct 7, 2019 in Vue.JS
Jan 9 in Vue.JS
Jan 9 in Vue.JS
...