My JSON data looks like:
{
"color-1": "#8888",
"color-2": "#000"
}
How can I bind this variable with style tag for vue ponent?
I am trying to use it in the following way, but its not working.
<div v-bind:style="{ color: data['color-1'] }"></div>
My JSON data looks like:
{
"color-1": "#8888",
"color-2": "#000"
}
How can I bind this variable with style tag for vue ponent?
I am trying to use it in the following way, but its not working.
<div v-bind:style="{ color: data['color-1'] }"></div>
Share
Improve this question
asked Apr 15, 2017 at 8:52
Mukesh BiswasMukesh Biswas
633 silver badges8 bronze badges
5 Answers
Reset to default 3You can access all data properties via $data:
{ "color-1": $data["color-1"] }
You would generally access your ponent's data
properties in the template by directly referring to them, without prefixing this.
or data.
. In your case, that's a problem, because it prevents you from using bracket notation.
You have two solutions:
Solution 1: Don't put your JSON data directly in the ponent data
, wrap it in an object (e.g. colors
). This way, using colors['color-1']
in the template will work.
Solution 2: Leave your data as is and write a simple method for getting properties in your ponent, then call it from the template. Something like:
methods: {
getProperty: function (name) {
return this[name];
}
}
And then in the template:
<div v-bind:style="{ color: getProperty('color-1') }"></div>
Had a similar issue. Here's how to fix it:
<div v-bind:style="{ color: this['color-1'] }"></div>
You can have hyphen-separated properties as strings.
<div v-bind:style='{ "color-1": data["color-1"] }'></div>
Docs
After finding some more details into similar problem, here is what I found here
Since v-bind
expects a javascript expression, you can't use -
in identifiers. If you really want to use -
, you can use v-bind:src="this['image-src']"
because this
is accessible in templates.
Hope it helps!