当我使用 v-bind:style 来使用动态值时,我遇到了 v-bind:style 不起作用的问题,但我确信 v-bind:style 得到了正确的值(:style='{控制台中的 color : red(任何其他值) }') 和样式部分中的 css 反映成功。为什么不使用 v-bind 呢?任何想法 ??非常感谢。
<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];
}
},
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
请检查以下代码片段,看起来一切正常:
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]; } }, })如上所述,您应该使用
compulated属性作为样式。这也会自动反映道具的任何变化。
如果您有某些条件,您还可以根据计算的回调函数中的值修改这些值。我添加了一个暗模式示例来阐明这种方法。
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: { // Here comes your style magic. // Return an Object that you will bind to the style prop. // Changes to any reactive value will be reflected directly. style(){ // create the base style here. let newStyle = {} // apply your titleColor1 which results in style="{color:titleColor1}" if(this.titleColor1){ this.color = this.titleColor1 } // if you would have more conditions you can add them here, too // just an _example_ if you would have a darkmode value in data. if(this.darkmode){ this.backgroundColor = '#222222' } return newStyle } }, methods: { // rest of methods if } }然后使用
:style="style"将其附加到您的 div。我这边的提示。我将外包用于设置颜色的代码并将该方法绑定到更改颜色的事件,而不是使用观察器。这可以使您的应用程序更加灵活并清理它。但您的做法也有效。