When I use v-bind:style to use dynamic values, I encountered the problem that v-bind:style does not work, but I am sure that v-bind:style gets the correct value (:style='{ color : red (any other value) }') in the console and css in the styles section reflect successfully. Why not use v-bind? Any ideas? ? Thank you so much.
<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]; } },
Please check the following code snippet, everything looks fine:
As mentioned above, you should use the
compulated
attribute for styles.This will also automatically reflect any changes to the prop.
If you have certain conditions, you can also modify the values based on the calculated values in the callback function. I've added a Dark Mode example to illustrate this approach.
Then use
:style="style"
to append it to your div.Tips from my side. Instead of using an observer, I would outsource the code for setting the color and bind that method to the event that changes the color. This can make your application more flexible and clean it up. But what you do works too.