Building Your First Component

Components are the building blocks of Vue applications. Let's create one!

What is a Component?

A component is a reusable piece of UI. Think of it like a custom HTML element you create yourself.

Creating a Simple Component

Let's create a button component:

<!-- components/MyButton.vue -->
<template>
  <button class="btn" @click="handleClick">
    {{ label }}
  </button>
</template>

<script setup>
// Props - data passed from parent
const props = defineProps({
  label: {
    type: String,
    default: 'Click me'
  }
})

// Events - communicate with parent
const emit = defineEmits(['click'])

function handleClick() {
  emit('click')
}
</script>

<style scoped>
.btn {
  padding: 0.5rem 1rem;
  background: blue;
  color: white;
  border: none;
  border-radius: 0.25rem;
  cursor: pointer;
}

.btn:hover {
  background: darkblue;
}
</style>

Using the Component

<template>
  <div>
    <MyButton 
      label="Say Hello" 
      @click="handleButtonClick"
    />
  </div>
</template>

<script setup>
function handleButtonClick() {
  alert('Button clicked!')
}
</script>

Key Concepts

Props (Data In)

Props let you pass data from parent to child:

<MyButton label="Custom Label" />

Events (Data Out)

Events let children communicate with parents:

<MyButton @click="doSomething" />

Slots (Content Projection)

Slots let you pass HTML content:

<!-- Component -->
<template>
  <button>
    <slot>Default text</slot>
  </button>
</template>

<!-- Usage -->
<MyButton>
  <strong>Bold text!</strong>
</MyButton>

Auto-Import in Nuxt

In Nuxt, components in components/ are automatically available - no imports needed!

Just create components/MyButton.vue and use <MyButton> anywhere.

Best Practices

  1. Keep components small - Each component should do one thing
  2. Use props for configuration - Make components flexible
  3. Name props clearly - isActive is better than state
  4. Document your components - Add comments explaining props

Conclusion

Components make your code reusable and maintainable. Start small, build up your component library! 🎨