Creating Components

Components are reusable Vue instances with a name and are uses through custom elements. Components can be defined by directing calling the component method from the Vue class.

NOTE

Later in the course, we will discuss how to use Vue files to create components.

// Define a new component 
Vue.component('simple-button', {
  template: `<button class="btn btn-primary">Click me!</button>`
})

new Vue({ el: '#app' })
<div id="app">
  <simple-button></simple-button>
</div>

In the example above, the simple-button component does do much. It is only a template. But a component can be so much more. It can have data, methods, and computed properties.

Adding data to a component is slightly different in that the data option must be a function.

Vue.component('simple-button', {
  data: function () {
    return {
      text: 'Click Me',
      type: 'success'
    }
  },
  template: `<button class="btn" :class="'btn-'+type">{{ text }}</button>`
})

new Vue({ el: '#app' })
<div id="app">
  <simple-button></simple-button>
</div>

Of course, the above button is only slightly better. However, it still a very simple button, which doesn't do much.

But the biggest advantage of using a component is its reusability. It is easy to create more buttons by simple adding the custom element multiple times.

Vue.component('simple-button', {
  data: function () {
    return {
      text: 'Click Me',
      type: 'success'
    }
  },
  template: `<button class="btn m-1" :class="'btn-'+type">{{ text }}</button>`
})

new Vue({ el: '#app' })
<div id="app">
  <simple-button></simple-button>
  <simple-button></simple-button>
  <simple-button></simple-button>
</div>