Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

p0k3rface's avatar

Passing styles through props (Composition API)

Hello, how can I make my button component reusable? I want to set it's background color and text color in components where I use this button.

Button :

<template>
  <div>
    <button
      class="text-white pt-2 pb-2 pr-7 pl-7 bg-bgColor border rounded-lg border-white"
    >
      <slot></slot>
    </button>
  </div>
</template>

<script>
export default {
  props: ["bgColor"],
};
</script>

Here I want to use it:

<template>
  <div>
    <section>
      <h3 class="text-white text-lg">Example</h3>
    </section>
    <section>
      <the-button>Example</the-button>
      <the-button>Example</the-button>
    </section>
  </div>
</template>

<script setup>
import TheButton from "@/components/ui/TheButton.vue";

const props = defineProps(["text"]);
console.log(props.text);
</script>
0 likes
6 replies
tykus's avatar

Use v-bind for the dynamic class name part:

<button 
  class="text-white pt-2 pb-2 pr-7 pl-7 border rounded-lg border-white" 
  :class="`bg-${bgColor}`"
>
1 like
p0k3rface's avatar

@tykus And how should I set it in the component?

      <the-button bg='red-500'>Example</the-button>

tried like this but doesnt work

tykus's avatar

@p0k3rface well the prop in the component is named bgColor, so:

<the-button bg-color='red-500'>Example</the-button>
p0k3rface's avatar

@tykus yup I fixed that but it still doesn't work, console.log shows that it exists on first render and then its undefined.

@kiri1101 that works, thanks!

kiri1101's avatar
kiri1101
Best Answer
Level 5

@p0k3rface here is an example using the composition API

<script setup>
defineProps({
  buttonTitle: {
    type: String,
    required: true,
  },
  classes: {
    type: String,
    required: false,
  },
});
</script>

<template>
  <button
    type="button"
    class="px-9 py-2 flex-none h-12 uppercase text-md font-medium font-sans"
    :class="classes"
  >
    {{ buttonTitle }}
  </button>
</template>
kiri1101's avatar

Then all you do is import your component

<script setup>
import IconButton from "./icons/IconButton.vue";
</script>

<template>
   <IconButton
       buttonTitle="Shop Now"
       classes="text-black bg-white hover:text-white hover:bg-black"
    />
</template>

Please or to participate in this conversation.