How to Create a Component in Vue: Simple Guide
In Vue, you create a component by defining a
<template> for the HTML structure and a <script setup> block for logic using the Composition API. Then you register and use the component inside other Vue components or your app.Syntax
A Vue component typically has a <template> section for HTML, a <script setup> block for JavaScript logic, and optionally a <style> block for CSS. The script setup syntax is the modern, concise way to write components.
- template: Defines the HTML structure.
- script setup: Contains reactive data, functions, and imports.
- style: Optional CSS scoped to the component.
vue
<template> <div>Hello, Vue Component!</div> </template> <script setup> // JavaScript logic here </script> <style scoped> /* CSS styles here */ </style>
Output
Displays: Hello, Vue Component!
Example
This example shows a simple Vue component named GreetingMessage that displays a greeting message. It uses script setup to define a reactive message variable.
vue
<template>
<h1>{{ message }}</h1>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello from Vue Component!')
</script>
<style scoped>
h1 {
color: #42b983;
font-family: Arial, sans-serif;
}
</style>Output
Displays a green heading: Hello from Vue Component!
Common Pitfalls
Common mistakes when creating Vue components include:
- Forgetting to use
reforreactivefor reactive data, so changes don't update the UI. - Not using
script setupsyntax properly, causing errors. - Missing the
scopedattribute on styles, which can cause CSS to leak globally. - Not registering components correctly when using them inside other components.
vue
<!-- Wrong: Missing ref for reactive data --> <script setup> const count = 0 // This won't update the UI </script> <!-- Right: Using ref for reactive data --> <script setup> import { ref } from 'vue' const count = ref(0) // Reactive and updates UI </script>
Quick Reference
| Concept | Description |
|---|---|
| Defines the HTML structure of the component | |
| Contains component logic using Composition API | |
| ref() | Creates reactive data that updates the UI |
| scoped styles | CSS that applies only to this component |
| Component registration | Import and declare components to use them |
Key Takeaways
Use
<template> and <script setup> to create Vue components with the Composition API.Wrap reactive data with
ref() or reactive() to make the UI update automatically.Add
scoped to <style> to keep styles local to the component.Always register components properly before using them inside other components.
Keep component code simple and focused on one task for easier reuse.