General and Custom Components
Learn about general and custom components in Vue.
We'll cover the following
Overview
As we know, Vue is designed for creating component-based UIs. The idea is that we can structure our application around self-contained, reusable elements that represent a discrete part of the interface.
One example of this might be an avatar component that displays a user’s profile picture as a circular image. Once created, this component can be dropped into our application code anywhere we want to display the user’s avatar.
<div class="sidebar"><avatar :src="user.image" /><h2>{{ user.nick }}</h2></div>
As we can see in the example abovr, using a Vue component in our templates is like having a new HTML element available: we use the component’s name as the tag (<avatar>
, in this case) and pass in any data it needs in the form of custom attributes. Here, a URL is passed as the src
attribute.
Custom components
We can define the custom components in a Vue app. The Vue object provides a component()
method that can be used to register new components by passing a name and an options object as follows:
Vue.component('MyCustomComponent', {// ...});
Naming a component
We can choose the kebab case (my-component) or Pascal case (MyComponent) when naming our component. Because Pascal case allows us to use either naming style when referencing our component within a template, it’s highly recommended by the community to use Pascal case for naming a component.
Note: It’s important to note that when using our component directly in the DOM, only the kebab case tag name is valid.
Registering a component this way makes it available anywhere in our Vue app for other components to use within their templates. This is very handy for components (for example, general layout components) that we’re going to be using a lot throughout our app.
When using single-file components, it’s possible to import and use them directly within the components where they’re needed.