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:
constCustomButton={template:'<button>Custom button</button>'};
That’s it. You can then pass this component into your app by using the components objects:
<divid="app"><custom-button></custom-button></div><script>constCustomButton={template:'<button>Custom button</button>'};newVue({el:'#app',components:{CustomButton}});</script>
This outputs the custom button to the page.
You can also register ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access