Creating components
A component is a reusable custom element with its own template, data and logic.
In this page:
Syntax
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
<!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
- Using single-word names that clash with HTML
- Forgetting to register the component
- 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: