Building Reusable Components in Vue 3

Reusable components improve maintainability and consistency in your application.

Creating a Reusable Component

A reusable button component:

<template>
  <button :class="buttonClass" @click="$emit('click')">
    <slot>Default Text</slot>
  </button>
</template>

<script>
export default {
  props: {
    type: { type: String, default: 'primary' },
  },
  computed: {
    buttonClass() {
      return `btn-${this.type}`;
    },
  },
};
</script>

Using the Reusable Component

<MyButton type="secondary" @click="handleClick">Click Me</MyButton>

Leave a comment

Your email address will not be published. Required fields are marked *