javascript - 有没有一种方法可以使用 rgba 颜色 [0, 15, 31, 0.4 ] 在 vue js 中设置 TD 元素的样式

标签 javascript css vuejs2

我有这段代码,目标是设置 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/

相关文章:

javascript - 如何计算生成的所有数字?

iphone - iOS 有哪些字体,是否支持@font-face?

javascript - 使用 nuxt-child 仅一层的 Nuxt 动态嵌套路由

javascript - DateTime 奇怪的转换

javascript - 为什么 "document.styleSheets"在浏览器每刷新 3 到 5 次后返回空值?

javascript - 查询 |如何从选择的html元素中获取选定的项目

vue.js - 不能在 VueJS 中的有状态组件根元素上使用 v-for

jquery - 如何将图标添加到多选?

html - 我的页脚不会位于底部

javascript - Vue.js : How to fire a watcher function when a component initializes