0
0
VueHow-ToBeginner · 3 min read

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 ref or reactive for reactive data, so changes don't update the UI.
  • Not using script setup syntax properly, causing errors.
  • Missing the scoped attribute 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

ConceptDescription