我有这段代码,目标是设置 TD 元素的样式:
<table >
<tr>
<td
v-for="(color, index) in colors"
:key="index"
:style="{backgroundColor: color}"
>
</td>
</tr>
</table>
color
是一个 rgba 颜色数组,如 [ [0, 15, 31, 0.4], [0, 20, 31, 0.4], .. ]
代码无效。只有当我将“颜色”数组的类型更改为 HEX 时,它才有效。
最佳答案
使用返回 RGBA 字符串的方法,然后将该方法绑定(bind)到 style
属性。
在下面这个稍微高级一点的示例中,您使用了 ES6 的 array destructuring。和 template literals生成你想要的 RGBA 字符串:
<table>
<tr>
<td
v-for="(color, index) in colors"
:key="index"
:style="tdCssStyle(color)"
>
</td>
</tr>
</table>
然后在你的组件 JS 逻辑中:
methods: {
tdCssStyle: function(color) {
const [r, g, b, a] = color;
return {
backgroundColor: `rgba(${r},${g},${b},${a})`
};
}
}
注意:您的 v-for
绑定(bind)中有错字,您缺少 in
关键字,即它应该是 (color, index) in颜色
。
概念验证:
new Vue({
el: '#app',
data: {
colors: [
[0, 15, 31, 0.4],
[0, 20, 31, 0.4]
]
},
methods: {
tdCssStyle: function(color) {
const [r, g, b, a] = color;
return {
backgroundColor: `rgba(${r},${g},${b},${a})`
};
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<table>
<tr>
<td v-for="(color, index) in colors" :key="index" :style="tdCssStyle(color)">
{{ color }}
</td>
</tr>
</table>
</div>
关于javascript - 有没有一种方法可以使用 rgba 颜色 [0, 15, 31, 0.4 ] 在 vue js 中设置 TD 元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56272279/