PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 24, 2022

[FIXED] How bind data in vue.js when my key consists dash (-) in JSON data?

 July 24, 2022     javascript, json, vue.js     No comments   

Issue

My JSON data looks like:

{
    "color-1": "#8888",
    "color-2": "#000"
}

How can I bind this variable with style tag for vue component?
I am trying to use it in the following way, but its not working.

<div v-bind:style="{ color: data['color-1'] }"></div>

Solution

You would generally access your component'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 component 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 component, 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>


Answered By - mzgajner
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,259,528

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing