Skip to content

What Is a Vue Component?

A Vue component is a structure in the Vue.js framework that represents a reusable, customisable element. Vue is a JavaScript framework for building user interfaces, and components are how it splits the UI into reusable, independent and manageable pieces.

Vue components usually have these parts:

  1. Template: an HTML-based template that defines the component's markup and structure.
  2. Data: each component manages its own data, which controls its behaviour and appearance.
  3. Methods: functions that react to events or perform specific tasks.
  4. Lifecycle hooks: components can react to moments of their life such as creation, update and removal.
  5. Styles: CSS (or another style language) for styles that belong to the component.

Components are designed to be reusable, easy to maintain and independent. In large applications this reduces complexity and keeps the code modular.

Here is a simple Vue component:

Vue
<template>
  <div>
    <h1>{{ message }}</h1>
    <button @click="changeMessage">Change message</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello, Vue.js!',
    };
  },
  methods: {
    changeMessage() {
      this.message = 'New message!';
    },
  },
};
</script>

<style scoped>
/* Styles that belong to this component */
h1 {
  color: blue;
}
</style>

This component shows a message and changes it when the button is clicked. It can then be used in other Vue files.

Have a question about this article? Write to me