← Back to Vue.js Course | Chapter 4: Components | Lesson 1 of 7

Creating components

A component is a reusable custom element with its own template, data and logic.

In this page:

  1. Creating components
Syntax
markup
const app = Vue.createApp({});
app.component('component-name', {
  template: '<div>{{ message }}</div>',
  data() { return { message: 'text' }; }
});

<component-name></component-name>

Creating components

Register a component with app.component(name, definition) and use it like an HTML tag. Each usage is an independent instance. Components let you split the interface into small, testable, reusable pieces.

Note: Use multi-word names to avoid clashing with native HTML elements.

Example: Creating components

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <hello-card></hello-card>
  <hello-card></hello-card>
</div>
<script>
  const app = Vue.createApp({});
  app.component("hello-card", {
    data() { return { likes: 0 }; },
    template: '<div style="border:1px solid #ccc;padding:6px;margin:4px"><b>Hello!</b> <button @click="likes++">Like {{ likes }}</button></div>',
  });
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Hello! Like 0Hello! Like 0
-->
Live Example
Related Topics
Common Mistakes
  1. Using single-word names that clash with HTML
  2. Forgetting to register the component
  3. Sharing state accidentally through a non-function data
Chapter Summary
  • app.component registers a component
  • Use it as a custom tag
  • Each instance is independent
  • Use multi-word names
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.