You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中如何在style属性引用JS变量?动态设置div背景色

解决Vue动态绑定背景色不生效的问题

你当前的写法是把row.background_color当作普通字符串传递给style属性,Vue不会解析这个静态字符串里的变量,所以背景色无法正确应用。以下两种方法可以解决:

方法一:使用Vue的style对象绑定(推荐)

用:style(v-bind:style的简写)结合对象语法,直接将变量绑定到样式属性:

<div v-for="row in graphQL_result.table" class="grid">
  <div class="box" :style="{ background: row.background_color }">
    <!-- 你的表单内容 -->
  </div>
</div>

方法二:使用模板字符串绑定

如果更习惯字符串式的写法,可通过ES6模板字符串插入变量,同样要配合:style:

<div v-for="row in graphQL_result.table" class="grid">
  <div class="box" :style="`background: ${row.background_color}`">
    <!-- 你的表单内容 -->
  </div>
</div>

注意:确保row.background_color的值是有效的CSS颜色格式(如#ffffff、blue、rgba(0,0,0,0.5)等),否则即使绑定正确也无法显示预期效果。

内容的提问来源于stack exchange,提问作者user5392022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:51:37