I’m stuck with a vue.js component inline style concatenation. My code is the following:
components: {
'twitter-item': {
props: ['procolors'],
template: '
<div class="color-quadrat" v-bind:data-id="procolors.id" v-bind:style="background-color: #{procolors.user.profile_background_color}">
<p>{{procolors.user.profile_background_color}}</p>
</div>
'
}
}
I’m trying to get procolors.user.profile_background_color
as inline background color. Special is that the value from procolors.user.profile_background_color
has no #
. So I have to add this in the template.
I tried all kinds of recommendations from the web, but none worked for me.
Any help appreciated!
Advertisement
Answer
You have several choices in how to add styling. If you use v-bind:style="..."
, or it shorthand :style="..."
, you need to pass either a valid string, valid variable or a valid object.
Currently you are trying to parse background-color: #{procolors.user.profile_background_color}
as javascript, which is not going to work.
You can use a javascript template to create a string:
components: {
'twitter-item': {
props: ['procolors'],
template: '
<div class="color-quadrat" v-bind:data-id="procolors.id" v-bind:style="`background-color: #${procolors.user.profile_background_color}`">
<p>{{procolors.user.profile_background_color}}</p>
</div>
'
}
}
It is often more readable to refactor it to use a variable or function instead:
components: {
'twitter-item': {
props: ['procolors'],
template: '
<div class="color-quadrat" v-bind:data-id="procolors.id" v-bind:style="rowColor">
<p>{{procolors.user.profile_background_color}}</p>
</div>
',
computed: {
rowColor () {
return {
"background-color": `#${this.procolors.user.profile_background_color}`
}
}
}
}
}