Vue essentials - Components

In this video, I want to introduce you to one of the most important and fundamental concepts of the Vue framework, and that is components.

Components help you to extend basic HTML elements to allow for code reuse and to provide a more scalable architecture.

Said another way, in addition to the standard HTML elements that are available, e.g. paragraphs, divs, tables, and so on, components let you create your own custom elements for more flexible UI composition.

Registing components

One way to create a component is to use the Vue component API, which you can see we've used on line 11.

You'll give your component a tag name it can be referenced by (preferably in kebab case e.g. "my-component") and you'll provide a definition object for defining it.

examples/components.html

import { createApp } from "vue";
app = createApp();

app.component("my-component", {
  ...
});

Component definition

The first important attribute of Vue components is that they need to display something. In simple components, you can just supply a string or string literal containing markup, and assign that to a template property in the component definition, which we've done on line 12 - this component will simply display a div with a text interpolation.

Besides the template, you can give your component almost any property that you would give to a Vue instance. On lines 13-15, we've given this component a data property, but we could also give it a computed property, methods, lifecycle hooks or whatever.

In fact, you might think of a component as a mini, resuable instance of Vue.

examples/components.html

import { createApp } from "vue";
app = createApp();

app.component("my-component", {
  template: `<div>{{ msg }}</div>`,
  data: () => ({
    msg: "A custom component!"
  })
});

Using components

Once you've registered a component it's ready to be used in your index.html file or in any other template in your app.

Since Vue now recongizes your component, you can use it in your markup just like you would any other HTML element, as we've done on line 5.

examples/components.html

<div id="app">
  <my-component></my-component>
</div>

Once this app is run, the my-component element is replaced with the rendered template - a div and the value we assigned to the message data property. You can see that on line 27.

examples/components.html

<div id="app">
  <div>A custom component!</div>
</div>

Reusability

One of the key features of components is that they are resuable. Now that we've defined my-component, we can use it over and over again throughout our app.

So we could include a second instance, just like we could with any HTML element. And of course, each instance will have it's own independent state.

examples/components.html

<div id="app">
  <my-component></my-component>
  <my-component></my-component>
</div>

In the next video, we'll start creating our first components in the course project.


Click to load comments...