Change color on only one instance of a component

Hello,

I have component, namely a button, that I use several times. On one of these instances I want to change the background color. How can I do that ?

Code for the button:




{{ text }}



I want to change “primary-button-b-t-n” from the caller of this component.

The code provided is currently not properly formatted for this forum. In its current state it’s illegible which makes it hard for people to help you.

Please read the following guide about how to properly format code and then edit your topic accordingly.

Thanks!

when you call this component you can send data.
for example -

<primary-button :color="red"></primary-button>

after in this component in props you use “color”
next in template in class use the props.

<div class="primary-button-btn" :class="color">{{text}}</div> or 
<div :class="'primary-button-btn ' + color">{{text}}</div>

that was what I was looking for, thank you

Hi @TimotheeWright
I have also tried it using props,
if you try to use mounted hook to change the styling according to the component, the mounted is not called for other instance of the component, so inline styling also works. we can use v-bind in style and use the prop.
App.vue

<template>
  <HelloWorld /><br />
  <HelloWorld color="yellow" /><br />
  <HelloWorld color="green" />
</template>

<script>
import HelloWorldVue from "./components/HelloWorld.vue";
export default {
  name: "App",
  components: {
    HelloWorld: HelloWorldVue,
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

helloworld.vue

<template>
  <div>
    <button id="btn" :style="{ 'background-color': color }">
      {{ color }}
    </button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    color: {
      type: String,
      default: "red",
    },
  },
  data() {
    return {
      ccolor: [1, 2, 3, 4],
    };
  },
  methods: {
    chngArray() {
      console.log(this.ccolor);
    },
  },
  // mounted() {
  //   document.getElementById("btn").style.backgroundColor = this.color;
  // },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

This is an alternative solution by using the props.

src code link: clever-violet-8s24of - CodeSandbox