最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How bind data in vue.js when my key consists dash (-) in JSON data? - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 3

You 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!

发布评论

评论列表(0)

  1. 暂无评论