DEV Community

ktr92
ktr92

Posted on

[vue3 ts tailwind] Simple reusable Button component example

/components/UI/Button.vue

<template>
  <button
    @click.prevent="onClick"
    :disabled="props.disabled"
    :class="classes"
    class="
      text-white
      bg-green
      hover:bg-blue-800
      focus:ring-4
      focus:outline-none
      font-medium
      px-5
      py-4
      text-md text-center
      cursor-pointer
      whitespace-nowrap
    "
  >
    <slot></slot>
  </button>
</template>

<script setup lang="ts">
const props = defineProps({
  disabled: {
    type: Boolean,
    default: false,
  },
  size: {
    type: String,
    default: "md",
  },
  liquid: {
    type: Boolean,
    default: false,
  },
  rounded: {
    type: Boolean,
    default: false,
  },
})

const emits = defineEmits(["onclick"])

enum ButtonSizes {
  "xs" = "px-[10px] py-[6px]",
  "sm" = "px-[15px] py-[10px]",
  "md" = "py-3 px-3",
  "lg" = "px-12 py-3",
}

enum TextSizes {
  "xs" = "text-xs",
  "sm" = "text-sm",
  "md" = "text-md",
  "lg" = "text-lg",
}

const paddingClasses = computed(() => {
  return ButtonSizes[props.size as keyof typeof ButtonSizes]
})

const textClass = computed(() => {
  return TextSizes[props.size as keyof typeof ButtonSizes]
})
const widthClass = computed(() => {
  return props.liquid ? "w-full" : "w-min"
})
const roundedClass = computed(() => {
  return props.rounded ? "rounded-md" : ""
})

const classes = computed(
  () =>
    `${paddingClasses.value} ${textClass.value} ${widthClass.value} ${roundedClass.value}`
)

const onClick = (event: Event) => {
  emits("onclick", event)
}
</script>

Enter fullscreen mode Exit fullscreen mode

Usage:

<UIButton
  @onclick="$emit('dosomething')"
  size="lg"
  :liquid="false"
  :rounded="true"
 >
   Do something
</UIButton>

Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay