Vue3中动态设置<span>元素style属性失效问题排查
问题原因及解决方案
问题根源
Vue的v-bind:style(缩写:style)不支持直接传入字符串格式的样式规则,它仅接受对象格式(或包含多个样式对象的数组)。你当前返回的是类似"background-color: blue"的字符串,不符合Vue对style绑定的格式要求,因此<span>的style属性被置为空,且由于没有语法错误,控制台不会抛出报错。
修复方法
修改determineColorOfLine方法,让它返回对象格式的样式定义:
determineColorOfLine(response){ console.log(response) // 使用驼峰式命名(Vue推荐写法) return { backgroundColor: response } // 也可以用短横线命名,需给键名加引号 // return { 'background-color': response } }
简化写法(可选)
如果逻辑简单,也可以直接在模板中写样式对象,省去方法调用:
<span v-else class="a" :style="{ backgroundColor: response }"> {{ response }} </span>
内容的提问来源于stack exchange,提问作者Selphiron
相关产品推荐
相关产品推荐

