Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making dynamic background colors in loop

I have an iteration through color_attributes :

  <div v-for="colorAttribute of selectedProduct.color_attributes" :key="selectedProduct.id">
      <span class="color-attribute" style="background: #{{colorAttribute}}"></span>
  </div>

How I can change the span background-color dynamically ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use template literals to bind the color property value dynamically.

Demo :

new Vue({
  el: '#app',
  data: {
    selectedProduct: {
        color_attributes: ['green', 'blue', 'yellow']
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(colorAttribute, index) of selectedProduct.color_attributes" :key="index">
      <span class="color-attribute" :style="`background: ${colorAttribute}`"> {{ colorAttribute }} </span>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading