I'm working with a Vue Component and I want to enhance it by binding a color to a specific message. Initially, I attempted to achieve this using a binding like
:style="styles"
However, I encountered the following error:
The property or method "styles" is not defined on the instance but referenced during render. Ensure that this property is reactive, either in the data option, or for class-based components, initialize the property
or create specific color classes in the css file.
.color--1
This led to an error stating
"Cannot read property '2' of undefined"
Is there a way to dynamically bind the color of the class based on a number received from the API?
Below is my code snippet:
<template>
<div class="chat__message shadow" :class="{'chat__message--own': message.selfOwned, colorClass}" >
</div>
</template>
<script>
import moment from 'moment'
export default {
props: ['message'],
data(){
return{
time: '',
colorArray: ['hsl(210 , 82 , 50 )', 'hsl(130 , 50 , 51 )', 'hsl(337 , 50 , 46 )','hsl(133 , 50 , 65 )', 'hsl(28 , 50 , 70 )','hsl(180 , 50 , 59 )' , 'hsl(274 , 50 , 82 )'],
colorClass:'',
styles: {
'background-color' : this.colorArray[2]
},
}
},
created(){
this.time = moment(this.message.created_at).format('HH:mm');
this.setColorClass(this.message.matchPosition);
},
methods: {
setColorClass(number){
this.colorClass = "color--" + number ;
}
}
}
</script>
<style lang="scss">
.color{
&--1{background-color: hsl(210 , 82 , 50 );}
&--2{background-color: hsl(130 , 50 , 51 );}
&--3{background-color: hsl(337 , 50 , 46 );}
&--4{background-color: hsl(133 , 50 , 65 );}
&--5{background-color: hsl(28 , 50 , 70 );}
&--6{background-color: hsl(180 , 50 , 59 );}
&--7{background-color: hsl(274 , 50 , 82 );}
}
.chat{
&__message{
&--own{
background-color: hsl(201, 100%, 55%);
color: rgba(255,255,255,1);
text-align: right;
}}
</style>