Reputation: 151
This probably has a simple solution it's just been a while since I've used vue:
I'm trying to pass data that's pulled from a list of colors into inline css to change the background color of each item, here's an example:
<ul>
<li v-for="color in colors">{{ color.value }}</li>
</ul>
<script>
new Vue({
el: '#main',
data: {
colors: [
{ value: '#00205b'},
{ value: '#0033a0'},
{ value: '#0084d4'}
],
}
})
</script>
I'd like to use the data pulled from color.value
and place it into something like v-bind:style="background-color: { color.value }"
but I can't figure out how to get this to work.
Upvotes: 0
Views: 1510
Reputation: 85613
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}"
Upvotes: 5
Reputation: 26791
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/[email protected]/dist/vue.js"></script>
<ul id="list">
<li v-for="color in extendedColors" :style="color.style">
{{ color.value }}
</li>
</ul>
Upvotes: 0