Vue-loader component experiencing issues with applying dynamic CSS styling

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>

Answer №1

Give this a try,

export default {
     props: ['message'],
     data(){
         var self = this; // Including this line
         return{
             date: '',
             colorArray: ['hsl(10 , 72 , 40 )', 'hsl(140 , 30 , 41 )', 'hsl(297 , 49 , 56 )','hsl(100 , 30 , 75 )', 'hsl(38 , 60 , 80 )','hsl(200 , 32 , 61 )' , 'hsl(254 , 47 , 76 )'],
             shade:'',
             stylesColor: {
                 'background-color' : self.colorArray[1] // Edit needed here
             },
         }
     },
...

Answer №2

The code snippet you shared does not contain any HTML that references styles. Is it possible that another component is attempting to access the styles variable of this component?

Is there a way to dynamically bind the color of a class based on a number received from the API?

If you add cssEl to your component's data object, you can handle it like so:

watch: {
  // Track the color (or colors) retrieved from the API
  colorTakenFromApi () {
    // Remove the previous class, if it exists
    this.cssEl && this.cssEl.remove();
    // Create a DOM element and specify it as a stylesheet
    this.cssEl = document.createElement('style');
    this.cssEl.type = 'text/css';
    // Use a text template to insert the desired CSS rule
    this.cssEl.innerHTML = `
      .${this.cssClass} {
        background-color: `${this.colorTakenFromApi}`
      }
    `;
  }
}

It may be considered a workaround, but this is how I managed to update my CSS classes at runtime.

Answer №3

If you find yourself unable to access the variable this when initializing data, there is a workaround:

Start by declaring your styles object as an empty object.

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: {},
    }
},

Then, in the created lifecycle hook, set the initial style:

created() {
    this.time = moment(this.message.created_at).format('HH:mm');
    this.setColorClass(this.message.matchPosition);

    // Using Vue.set
    Vue.set(this, 'styles', {
        'background-color' : self.colorArray[2]
    });

    // OR Normal setting
    this.styles = {
        'background-color' : this.colorArray[2]
    };
},

Answer №4

If you're facing a problem and not sure if I understand it correctly, you can try using computed methods:

props: ['message', 'colorNumber'],
computed: {
   getColorClass () {
      return 'color--' + this.colorNumber
   }
},

In your template, you can use the following code:

<template>
    <div :class="{'chat__message shadow': true,
                  'chat__message--own': message.selfOwned,
                   getColorClass: true}" >
    </div>
</template>

If you want to maintain props as they were before, and the prop "message" will change, then consider using watch (deep kind) instead of computed methods.

However, if the message props remain constant after the page is loaded, you can store it in data() variables and utilize it in computed methods:

data(){
    return {
        colorNumber: '',
    }
},
mounted() {
   this.$nextTick(function () {
       // Code that will run only after the
       // entire view has been rendered

       this.colorNumber = this.message.matchPosition;
   })
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to disable auto rotation on a website when accessed from a mobile phone?

My current solution involves the following code: @media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { html{ -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -ms-transform: rotate(- ...

What is the best way to retrieve the modelValue from within a Vue 3 directive?

Here is a question: How can I access and update el.modelValue from a custom directive? directives: { currency: { mounted(el, binding, vnode, prevVnode) { console.log(vnode, prevVnode) el.oninput = (e) => { if (Numb ...

Creating a layout with 2 rows and 5 columns in Bootstrap 5 may not perfectly fit a 100% width and 100% height

Can someone assist in adjusting this Bootstrap 5 code to perfectly fill the entire screen of all 16:9 devices (mobile and desktop/1080p/2160p using Chrome browser) with 100% width and height? The goal is to eliminate horizontal and vertical scrolling. Desp ...

Having difficulty altering the font in the WordPress tinymce editor

I've been attempting to update the font in the WordPress tinymce editor, but I'm running into issues. First, I created a tinymce-custom-editor.css file with the following code: @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,7 ...

The use of asterisk (*) in importing dynamically

Hello everyone, I'm currently working on a project structure that looks like this: intranet ├── modules │ ├── storage │ │ ├── views │ │ └── route │ │ └── index.js │ │ │ ├── ...

The Vue application using Axios is sending data to an Express backend, but it is receiving

Introducing the main.js file of my Vue application, currently operating on localhost:8080 and attempting to send data to localhost:8081 (express.js) // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in ...

Vue 3 Single File Component experiencing a type error when assigning v-model to a textarea

I encountered an error in VSCode when trying to use v-model on a <textarea>. The error message states: (property) TextareaHTMLAttributes.value?: string | number | string[] | undefined Type 'Ref<string>' is not assignable to type &ap ...

Creating a responsive navigation menu using Bootstrap 4 by merging data from various MySQL tables

I am struggling to create a bootstrap 4 nav-menu using the provided SQL query and code snippets. Below are the tables: TABLE menu -------------------------------------- | id | title | url | | 1 | Home | index.php | | 2 | M ...

Tips on toggling the visibility of a div using jQuery and CSS via a toggle switch

Hey there, I need some help with toggling the opening and closing of a div when clicking on a toggle switch. $('.tog').on('click', function() { $('.cntr').show(); }); .switch { position: relative; display: inline-bloc ...

Utilize the display: flex property to position a div in the bottom right corner of its containing element

I'm trying to showcase a yellow div "icon" at the bottom right corner of its red container "content". Can someone help me figure out what's incorrect in my code? .root { display: inline-flex; background-color: red; } .content { d ...

Troubleshooting: Issues encountered with Laravel 8 gates when using Auth::guard

Hello, I am currently working on a project that involves assigning roles and permissions to users. I am using middleware to protect my routes by setting up Gates, but I keep getting a 403| Not Authorized error. Can anyone help me determine what the issue m ...

"Duplicate instances of the domain appear in the URLs of the images

After installing bagisto (a Laravel ecommerce app) on a fresh setup, I encountered an issue with the CMS where uploading a new logo to the channel would cause it to be added to the symlink. Despite everything appearing correctly in the public directory, th ...

Steps to place a URL and Buttons over an existing header Image

1) I am working with a header JPEG image that is 996px wide and includes a square logo on the left side. My goal is to use only this square logo section and add an href tag so that when users hover over it, the cursor changes to a hand pointer and they are ...

The process of ensuring a component is able to watch for the router even when it is not within the router

I am facing an issue with setting v-if for an element to get a boolean value from a function when the router changes the URL. Here is the code snippet for my Header component: <template> <header class="wfm-header"> <div class=" ...

Click-triggered CSS animations

Trying to achieve an effect with regular JS (not jQuery) by making images shake after they are clicked, but running into issues. HTML: <img id='s1_imgB' class="fragment"... onClick="wrongAnswer()"... JS: function wrongAnswer(){ docume ...

Perform a comparison of two JSON structures in PHP, identifying any missing elements in each and adding them with a default value

I have two JSONs that need to be compared in order to add missing elements from one JSON with a default value. Despite trying the code below, I'm facing an issue where both JSONs are being merged together. json1 = [{"id":1,"name": ...

Struggling with getting Bootstrap Affix-bottom to scroll back up?

Despite reading various answers, I am still struggling to configure the settings correctly. The columns header is not resuming scrolling upwards as expected. Below is my PHP code snippet: <div id="columnsHeader" class="affix" data-offset-top="800" da ...

Animate a div once the parent section becomes visible while scrolling

I previously had this function working, but it seems that I have somehow messed it up in the process. My current setup includes a scroll hijack feature that navigates users to a new section or card each time they scroll. The script adds a visible class w ...

Various formatting options on GitHub Pages

As a beginner in programming, I recently deployed my first project to github pages. However, I am facing two issues: While the desktop version of the site looks perfect, the cards on the home page appear unseparated on mobile and iPad devices. Despite try ...

Shifting Elements - Navigation triggers subtle movements in CSS styles as you move across pages

I've noticed a strange issue on my website where certain elements seem to be shifting slightly when navigating between different pages. Here's a quick video clip demonstrating the problem. It appears that these elements are not staying static as ...