html 动态设置vuejs3中的样式属性< span>

ep6jt1vc  于 2022-12-16  发布在  其他
关注(0)|答案(3)|浏览(318)

调用API后,我想根据响应创建元素,span的背景颜色由得到的响应决定,创建span元素如下:

<span v-else class="a" v-bind:style="determineColorOfLine(response)">
   {{ response }}

methods中有一个名为determineColorOfLine的函数

determineColorOfLine(response){
   console.log(response)
   return ("background-color: " + response)
}

我希望看到文本“response”和API请求响应的背景颜色(例如“blue”),但是背景颜色没有改变。当我检查span元素时,我看到

style=""

但我希望

style="background-color: blue"

在控制台中,我看到日志显示为“蓝色”,所以该方法可以运行。我没有看到任何错误。错误在哪里?

xxhby3vn

xxhby3vn1#

返回style="background-color: blue"将其绑定到内联样式实际上创建了语句style=style="background-color: blue"
请改为使用return 'background-color: ' + response;

ymdaylpp

ymdaylpp2#

使用计算属性

computed: {
    colorOfLine() {
        return { backgroundColor: this.response } 
    } 
}
<span :style="colorOfLine"...
e4eetjau

e4eetjau3#

您需要返回一个对象:

determineColorOfLine(response){
   console.log(response)

   // Make an object here
   return {"background-color": response}
}

相关问题