I have an iteration through color_attributes
:
<div v-for="colorAttribute of selectedProduct.color_attributes" :key="selectedProduct.id">
<span style="background: #{{colorAttribute}}"></span>
</div>
How I can change the span
background-color dynamically ?
CodePudding user response:
You could bind the style to the object :
<div v-for="colorAttribute of selectedProduct.color_attributes" :key="selectedProduct.id">
<span :style="{background: '#' colorAttribute}"></span>
</div>
or with string template:
<span :style="`background: #${colorAttribute}`">
CodePudding user response:
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 :style="`background: ${colorAttribute}`"> {{ colorAttribute }} </span>
</div>
</div>