Chapter 2. Components in Vue.js

You’ve seen me mention components a couple of times now, but what is a component? A component is a self-contained piece of code that represents a part of the page. Components have their own data, their own JavaScript, and often their own styling. They can contain other components, and they can communicate with each other. A component could be something as small as a button or an icon, or it could be something bigger, such as a form you reuse a lot throughout your site or an entire page.

The main advantage of separating your code into components is that the code responsible for each bit of the page is close to the rest of the code for that component. No more having to search for a selector in a ton of JavaScript files to see what is adding that event listener; the JavaScript is right there next to the HTML! Because components are self-contained, you also can make sure that none of the code inside a component will affect any other components or have any side effects.

Component Basics

Let’s dive right in and demonstrate a simple component:

const CustomButton = {
  template: '<button>Custom button</button>'
};

That’s it. You can then pass this component into your app by using the components objects:

<div id="app">
  <custom-button></custom-button>
</div>
<script>
  const CustomButton = {
    template: '<button>Custom button</button>'
  };

  new Vue({
    el: '#app',
    components: {
      CustomButton
    }
  });
</script>

This outputs the custom button to the page.

You can also register ...

Get Vue.js: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.