Skip to main content

Component in Vue.js

A component in Vue.js is a reusable, isolated piece of UI that combines a template (HTML), logic (JS), and styles (CSS) together. It lets you break an application down into small, understandable parts: buttons, forms, cards, modals, pages, and so on.

In simple terms: A component is a self-contained piece of UI with its own logic and state.


What is a component made of?

In modern Vue (Vue 3) a component is usually written as a Single File Component (SFC) - a .vue file made up of 3 blocks:

javascript
<template> <button @click="count++"> Clicked {{ count }} times </button> </template> <script setup> import { ref } from 'vue' const count = ref(0) </script> <style scoped> button { padding: 10px; } </style>

1. <template>

Describes the markup, i.e. what the component looks like.

2. <script setup>

Describes the component's logic:

  • data (state),
  • methods,
  • computed properties,
  • events,
  • imports, and so on.

3. <style>

The component's styles. scoped means the styles will apply only inside this component.


Why do components matter?

Reusability

Create a button once, insert it anywhere:

javascript
<MyButton />

Easy testing and maintenance

Each component is a small, independent part of the application.

Local state

A component holds its own copy of the data:

javascript
const counter = ref(0)

Each instance of the component will have its own state.

Logic isolation

A component decides for itself what it does and how.


How do you register a component?

Locally in an SFC (the most common way)

javascript
<script setup> import MyButton from './MyButton.vue' </script> <template> <MyButton /> </template>

Globally

javascript
import { createApp } from 'vue' import App from './App.vue' import MyButton from './components/MyButton.vue' const app = createApp(App) app.component('MyButton', MyButton) app.mount('#app')

A simple component example

Counter.vue

javascript
<template> <div> <p>Count: {{ count }}</p> <button @click="increment">+1</button> </div> </template> <script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script>

Usage:

javascript
<template> <Counter /> </template> <script setup> import Counter from './Counter.vue' </script>

Summary (in short)

A component in Vue is a small, independent part of the interface with its own markup, logic, and styles. It lets you:

  • break the application into logical parts,
  • reuse elements,
  • keep local state,
  • simplify testing and maintenance.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.