Components Basics

1/1/2025

Components Basics

Components allow us to split the UI into independent and reusable pieces, and think about each piece in isolation.

Defining a Component

When using a build step, we typically define each Vue component in a dedicated file using the .vue extension - known as a Single-File Component (SFC):

vue
<script setup>
import { ref } from 'vue'

const count = ref(0)
</script>

<template>
  <button @click="count++">You clicked me {{ count }} times.</button>
</template>

Using a Component

To use a child component, we need to import it in the parent component:

vue
<script setup>
import ButtonCounter from './ButtonCounter.vue'
</script>

<template>
  <h1>Here is a child component!</h1>
  <ButtonCounter />
</template>

Passing Props

Props are custom attributes you can register on a component:

vue
<script setup>
defineProps(['title'])
</script>

<template>
  <h4>{{ title }}</h4>
</template>

Emitting Events

Components can emit custom events:

vue
<script setup>
const emit = defineEmits(['submit'])

function handleClick() {
  emit('submit', { data: 'value' })
}
</script>