Using v-bind to dynamically set styles in Vue.js

While utilizing v-bind:style to apply dynamic values, I encountered an issue where v-bind:style did not seem to work. However, in the console, I verified that v-bind:style was receiving the correct value (:style='{ color : red (or any other value) }'). The CSS in the style section also reflected the changes successfully. Why is v-bind not working? Any suggestions are greatly appreciated. Thank you.

<div class="l-modal" v-if="modalVisible1">
      <div class="p-modal" @click="hide_modal" :style='{ color : titleColor1 }' ref="test">
        <p>{{titleTxt1}}</p>
        <p>{{contentTxt1}}</p>
        <p>{{endTxt1}}</p>
        <button class="p-modal__btn">{{buttonTxt1}}</button>
      </div>
</div>
<div class="l-modal__bg" v-if="modalBgVisible1" @click="hide_modal"></div>
data () {
    return {
      selected_title_color1:'',
      titleColor1:'',
      colors:['紅色','藍色','黃色','粉色','土地色','水藍色','灰色','淺綠色','橙色'],
      colors_dic:{紅色:'red',藍色:'blue',黃色:'yellow',粉色:'pink',土地色:'blawn',水藍色:'aqua',灰色:'gray',淺綠色:'palegreen',橙色:'orange'},
    }
},
watch:{
    selected_title_color1: function () {
      this.titleColor1 = this.colors_dic[this.selected_title_color1];
    }
  },

Answer №1

To achieve the desired result, it is recommended to utilize a computed property for handling the style modifications.
This method will automatically adapt to any changes in props.
In cases where specific conditions need to be met, adjustments can be made based on these conditions within the computed callback function. An example with darkmode has been included to illustrate this approach.

export default {
  data(){ return {
        selected_title_color1:'',
        titleColor1:'',
        colors:['紅色','藍色','黃色','粉色','土地色','水藍色','灰色','淺綠色','橙色'],
        colors_dic:{紅色:'red',藍色:'blue',黃色:'yellow',粉色:'pink',土地色:'blawn',水藍色:'aqua',灰色:'gray',淺綠色:'palegreen',橙色:'orange'},
        modalVisible1: true,
        darkmode: false, // example value
  }},

  watch:{
    selected_title_color1: function () {
      this.titleColor1 = this.colors_dic[this.selected_title_color1];
    }
  },

  computed: {
     // Implement your custom styling here.
     // Return an Object that will be bound to the style prop.  
     // Any changes in reactive values will be reflected immediately.  
     style(){
        // Define the base style here.        
        let newStyle = {}

        // Incorporate the titleColor1 which yields style="{color:titleColor1}"
        if(this.titleColor1){
          this.color = this.titleColor1
        }

        // Additional conditions can also be added here, such as a darkmode option.
        if(this.darkmode){
          this.backgroundColor = '#222222'
        }       

       return newStyle
    }
 },

 methods: {
    // Other methods can be included here 
 }
}

Assign this computed styling to your div using :style="style".

<div class="l-modal" v-if="modalVisible1">
     <div class="p-modal" @click="hide_modal" :style="style" ref="test">
       <p>{{titleTxt1}}</p>
       <p>{{contentTxt1}}</p>
       <p>{{endTxt1}}</p>
       <button class="p-modal__btn">{{buttonTxt1}}</button>
     </div>
</div>
<div class="l-modal__bg" v-if="modalBgVisible1" @click="hide_modal"></div>

A suggestion would be to extract the color-setting code into a separate method and link it to an event that triggers the color change instead of relying solely on a watcher. This can enhance flexibility and streamline the code, though your current implementation is functional as well.

Answer №2

Take a look at the code snippet below to see everything in action:

new Vue({
  el: "#demo",
  data () {
      return {
        selected_title_color1:'',
        titleColor1:'',
        colors:['紅色','藍色','黃色','粉色','土地色','水藍色','灰色','淺綠色','橙色'],
        colors_dic:{紅色:'red',藍色:'blue',黃色:'yellow',粉色:'pink',土地色:'blawn',水藍色:'aqua',灰色:'gray',淺綠色:'palegreen',橙色:'orange'},
        modalVisible1: true,
      }
  },
  watch:{
    selected_title_color1: function () {
      this.titleColor1 = this.colors_dic[this.selected_title_color1];
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div class="l-modal" v-if="modalVisible1">
      <div class="p-modal" :style='{ color : titleColor1 }' ref="test">
        <p>{{ titleColor1 }} - {{ selected_title_color1 }}</p>
      </div>
</div>
<select v-model="selected_title_color1">
  <option value="" disabled>Select color</option>
  <option v-for="option in colors" v-bind:value="option">
    {{ option }}
  </option>
</select>
</div>

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

switch between showing and hiding dynamic table rows

As I dynamically add rows to a table, each row can either be a parent row or a child row. My goal is to toggle the visibility of child rows when the parent row is clicked. if (response != null && response != "") { ...

How can I retrieve my array state in a different router page using VUEJS and VUEX?

I have created a page with two routes - one for the home page and another for the configuration where users can decide what content should be displayed on that container. In the configuration panel, I was able to retrieve input values and stored them in my ...

The div layer is positioned above the flash object

I have successfully implemented a method where I position a div over a webpage containing a flash object. This absolutely positioned div has a high z-index and captures click events. The main goal is to trigger the click event on the div when the flash obj ...

Exploring Javascript parameters with the power of jquery

Is it possible to pass a parameter from PHP into a JavaScript function within HTML? I am currently facing an issue where my code crashes when it reaches a certain condition. This is the code snippet causing the problem: $str="<input type='submit&a ...

Is there a way to automatically hide a div based on a checkbox value when the page loads?

How can I hide a div in my view when a checkbox is not checked upon page load? <input type="checkbox" class="k-checkbox" id="chkInvoiceStatusActive" asp-for="InvoiceStatus" value="true" /> <input t ...

Ways to show a child's component element within the parent container

Within my Angular 11 project, there exists a component that exhibits a child component containing assorted table filters: Parent Component <table-filters></table-filters> <table> ... </table> Child Component (table-filters) <f ...

Is it advisable to utilize media queries and transform: translateY(-%) to position content above the mobile keyboard?

I've been struggling for nearly a whole day and could really use some assistance. I'm having trouble understanding how chat web apps manage to work around this particular issue. There have been numerous forum posts discussing the problem: I am tr ...

Utilizing Omit for the exclusion of nested properties within a TypeScript interface

One of the components in a library I am using is defined like this: export interface LogoBoxProps { img: React.ReactElement<HTMLImageElement>, srText?: string, href?: LinkProps['href'] } export type LogoBoxType = React.FC<React.HT ...

Encountering a 401 error when submitting a form in Laravel Vue using Axios

Whenever I try to submit user data in my modal, I encounter a 401 error. Here is the code snippet that's causing the issue: sendUserData(){ axios.post('/api/saveUser', { headers: { ...

Next.js is causing an error by not recognizing the document variable

While diving into the world of next.js, I encountered an interesting challenge. In my project, I came across this puzzling error. The culprit seemed to be a module called Typed.js, which threw me off with a peculiar message: Server Error ReferenceError: d ...

What happens if I attempt to access an undefined value from a JSON array?

I've been attempting to nest a JSON array within another JSON array. I believe I have structured it correctly, but when I try to access the second array, it returns undefined. JSON example : var data = [ {"Items" : [ {"item1" : "item1 ...

React is unable to identify the `isDisabled` attribute on a DOM element within an img tag

After updating my React/Next.js App, I encountered the following issue: Upon investigation, React is indicating that the isDisabled prop is not recognized on a DOM element. To resolve this, you can either specify it as lowercase isdisabled if you want it ...

Create a new attribute within the ng-model object once it has been updated through ng-repeat

I am trying to figure out how to add a "discountRate" property to an ng-model object after it has been changed within an ng-repeat block. Check out this example for more information Another example can be found here Although the ng-model is updated as e ...

Displaying JSON data in a browser using Node.js without the need for refreshing the page

I am currently working on a node.js server that fetches JSON data from an external source and displays it in a browser window. I need assistance in setting up an automatic update every minute to reflect any changes in the JSON without requiring a manual re ...

Transforming objects into nested structures

After making a JSON call, I received the following JSON Object: [ { "feeding_id": 14, "supp_name": "Test 1", "supp_weight": 20000, }, { "feeding_id": 14, "supp_name": "Test 2", "supp_weight": 100 ...

Is there a syntax error in Javascript when using a string and variable with the GET method?

Is there a way to send a value using the get method? In JavaScript, we need to use the + symbol to concatenate strings. But my issue goes beyond this simple problem. If I attempt the following: Let's say; var sID = 16; var rID = 17; EDIT-2: I act ...

Angular.js reports that the custom HTTP response header is missing

Despite Chrome showing the correct POST response headers, my custom HTTP header X-Auth-Token is returning null in the callback function for the POST request. Angular.js seems to only be returning Cache-Control and Content-Type, with everything else showing ...

Unveiling the Power of Ionic and React for Component Repetition

I'm having trouble figuring out how to repeat my component multiple times using react in Ionic. Can someone assist me with this? Here's an example: In my Component.tsx file, I have the following code: import React from 'react'; import ...

This error is thrown when trying to access the property 'message' of an undefined value

I'm currently working on adding an AJAX contact form to my website. However, I've run into a problem where when I try to submit the form, I encounter the following error in Google Chrome: "Uncaught TypeError: Cannot read property 'message&a ...

Change the URL structure from ex.com/forum?id=1 to ex.com/#/forum?id=1 in AngularJS

Hey there! I'm in the process of creating a Forum using AngularJS and need some guidance. First things first! I've successfully established a connection to my database with: <?php session_start(); $db = new mysqli("localhost","root",""," ...