[Vuejs]-How can I use data from v-for list in inline css with v-bind:style?

5👍

You can use like this: (See style binding)

<li v-for="color in colors" v-bind:style="{backgroundColor: color.value}">
{{ color.value }}
</li>

Or,

:style="{'background-color': color.value}"

0👍

You can create a computed property and extend each color object in the colors array with a style property. This style property will contain the styling for each element.

Finally, use the computed property in the v-for directive instead of the original array.

new Vue({
  el: '#list',

  data() {
    return {
      colors: [{
          value: '#00205b'
        },
        {
          value: '#0033a0'
        },
        {
          value: '#0084d4'
        }
      ],
    };
  },

  computed: {
    extendedColors() {
      return this.colors.map(color => ({ ...color,
        style: {
          backgroundColor: color.value
        }
      }));
    },
  }
})
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<ul id="list">
  <li v-for="color in extendedColors" :style="color.style">
    {{ color.value }}
  </li>
</ul>

Leave a comment