Components

Published on Sep 10, 2022

Components are the building blocks of Vue.js applications. They are reusable, self-contained, and can be nested inside other components. They can be used in templates using the <component-name> syntax.

Components can be created in two ways:

  • Using Vue.component()
  • Using Vue.extend()

Both methods are equivalent, but Vue.extend() is more flexible and allows us to create components with more complex features.

Components are created in a separate file, usually inside the components and imported into the main application. However, they can be placed anywhere as long as the import path is accurate.

Vue.component

Given a simple Vue.js App:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>My App</title>
    <script src="https://unpkg.com/vue@latest"></script></head>
  <body>
    <div id="app">
      <h1>{{ greeting }}</h1>
    </div>
    <script src="./app.js"></script>
  </body>
</html>

main.js

const app = Vue.createApp({
  data() {
    return {
      greeting: 'Hello world'
    }
  }
});
const mountedApp = app.mount('#app');

We'll create a new file, WelcomeImage.js, inside the components folder:

components/WelcomeImage.js

app.component('welcome-image', {
  // component options
  template: '<img src="https://picsum.photos/200/300" />'
})

Notice, we're adding the component to the `app` variable. This is because we're using Vue.component() to create the component. We can then import the component into the main application.

Importing component

Inside the HTML file, we can import the component using the <script> tag, and use it:

index.html

...
  <body>
    <div id="app">
      <h1>{{ greeting }}</h1>
      <welcome-image></welcome-image>
    </div>
    <script src="./app.js"></script>
    <script src="./components/WelcomeImage.js"></script>
  </body>
</html>