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

I'm experiencing a challenge with Next.js where I am unable to use return within

My code was functioning properly with if-else statements in run dev, but encountered issues when running build. The if-else statements stopped working, prompting me to explore alternative ways of conditionally rendering a page. A new approach seemed promis ...

Using Vue the proper method to ensure the vuex store is accessible to a dynamically generated component

I have a .vue component called Sectors, that I need to dynamically add to a container named "desktop_sectors" on desktop, or "mobile" on mobile devices. <v-flex sm12 md12 ma-2 ref="desktop_sectors"> v-flex sm12 ma-2 ref="mobile"> To avoid crea ...

What is the best way to conceal a dropdown menu when the page first loads?

I have a dropdown menu that is displaying like this: <ul> <li class="dropdown open"> <a aria-expanded="true" href="#" class="dropdown-toggle waves-effect waves-button waves-classic" data-toggle="dropdown"> <spa ...

Incorporating a full-page background into a specific view using AngularJS

In order to implement a fullscreen CSS background for a specific view in my app, I attempted adding a class to the body. However, this approach caused the background to persist in the cache and remain visible when switching views. The challenge arises fro ...

Enhancing State Management with CombineReducers in TypeScript

export const rootReducer = combineReducers({ login: loginReducer, }); Everything is working fine with the current setup, but I encountered an issue when attempting to combine another reducer: export const rootReducer = combineReducers({ login: lo ...

Build a unique array of identifiers extracted from an object

I am seeking advice on how to extract an array of IDs values by iterating through an object in React JS. const initialState = useMemo(()=> { return dataTable.filter(result => favorites.some(favorite => result.id === favorite.id)) },[ ...

Tips for maximizing performance in ember-data through r.js

After making the switch to ember-data#canary, I encountered a problem with r.js failing. [Error: Error: ENOENT, no such file or directory '/scripts/lib/ember-data/ember-data/core.js' In module tree: app/main app/app embe ...

Tips for resolving the error message: 'The "path" argument must be a string. Received type undefined' that occurs when executing 'vue add vuetify'

After successfully creating a new app using 'vue create agenda', I proceeded to cd into the project folder and run 'vue add vuetify' to integrate Vuetify. However, I encountered an unexpected error. I attempted to search for solutions ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

Angular UI-Grid encountering difficulties in rendering secure HTML content

I'm having trouble displaying server-generated HTML in UI-Grid. Specifically, I want to show HTML content in my column header tooltips, but no matter what I try, the HTML is always encoded. Here's an example to illustrate the issue: var app = an ...

Retrieving information from an Express.js API using React.js. Postman requests are successfully communicating with the API

Hey there, I'm facing a little issue and could use some help. I have an Express application that is working perfectly with requests from Postman (adding, deleting, etc.). Now, I want to connect my client side (React.js) with the existing API using the ...

Ways to identify when a file download has finished with the help of javascript

let pageUrl = "GPGeneration_Credit.ashx?UniqueID=" + __uniqueId + "&supplierID=" + supplierID + "&CreditID=" + OrderIds; window.open(pageUrl); // Want to check if the file download is complete and then refresh the page location.r ...

What is the best way to embed a variable within a Directive HTML block for seamless access by the Controller?

I am facing a challenge with my custom directive that inserts an HTML block onto the page. The issue is to have a variable within this block that can be manipulated based on an ng-click function in my controller. This is what my directive looks like: .di ...

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...

Learn the process of using Angular Js to compare checkbox values with stored comma-separated values in a database

When displaying amenity checkbox options using ng-repeat of a JSON array and saving them into the database as comma-separated IDs like "1,3,7" within a single string, the challenge arises when needing to edit the amenities. This is due to retrieving the ex ...

Guide on accessing a nested array within a JSON object using JavaScript

I'm currently faced with a json object that contains nested arrays and names with spaces like Account ID. My goal is to only display the Account ID's within my Vue.js application. While I can access the entire response.data json object, I'm ...

Navigate to a particular date with react-big-calendar

I know this might sound like a silly question, but I am new to working with React. Currently, the React-big-calendar allows users to navigate to specific dates when selected from the Month view. What I want is for the same functionality to apply when a use ...

Concealing a form after submission using JavaScript

After submitting the form, I am attempting to hide it and display a loading GIF. I've experimented with various methods, including changing ClassName to Id, but haven't had success. This is for a school project, and I've spent a significant ...

Cross-Origin Request Sharing (CORS) problem encountered while making an API call with

My current challenge involves calling an API that returns data in XML format as a response. While testing the .htm file on my local machine, I encountered the following error. https://i.stack.imgur.com/FsvZ0.png Similarly, running it from the codepen.io ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...