"Can you provide guidance on binding data in vue.js when there is a dash (-) in the key of the JSON

My JSON data is structured as follows:

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

I am attempting to bind this variable with a style tag for a Vue component. However, my current approach seems to not be functioning as expected.

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

Answer №1

To view all data properties, use the $data variable:

{ "background": $data["background"] }

Answer №2

When working with components, accessing the properties of your data is typically done in the template by directly using their names, without needing to include this. or data.. However, this approach can be limiting when you want to utilize bracket notation for dynamic property access.

To address this issue, there are two potential solutions:

Solution 1: Instead of placing your JSON data directly into the component's data, encapsulate it within an object (e.g., colors). This allows you to access properties using bracket notation such as colors['color-1'].

Solution 2: Keep your data structure unchanged and create a simple method within your component that retrieves properties. You can then call this method from the template. For example:

methods: {
  getProperty: function (name) {
    return this[name];
  }
}

Subsequently, in the template, you would use:

<div v-bind:style="{ color: getProperty('color-1') }"></div>

Answer №3

Dealt with a comparable problem and found a solution:

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

Answer №4

You may include hyphen-separated attributes as strings.

<section v-bind:style='{ "background-color": content["background-color"] }'></section>

Documentation

Answer №5

Upon further investigation into a similar issue, I came across some additional information here

It appears that since v-bind requires a javascript expression, using - in identifiers is not allowed. However, if you absolutely need to use -, you can work around it by using v-bind:src="this['image-src']" as this is accessible in templates.

I hope this explanation proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Simulated external prerequisite

//user.js const database = require('database'); exports.createUser = function(req, res){ let user = req.body; if( validateUser(user) ) { database.insertUser(user); //redirect } else { //render new page with the user data ...

How can nested json be sorted effectively based on two specific fields?

Example Data: [{ 'ID': objID(abc123), 'Department': 'IT', 'Employees': [ { 'ID': 3, 'StartDate': '24-12-2022T08:30', 'active': true }, { ...

Issue with TinyMCE Editor: Inoperative

<script type="text/javascript" src="<your installation path>/tinymce/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", theme: "modern", plugins: [ "advlist autolink li ...

Using Vuetify to create subtle fade in animation when scrolling

I'm attempting to create a fade-in effect while scrolling through the page for the first time. Even though I used <v-scroll-x-transition appear>, the desired effect doesn't seem to be working. Instead of fading in from the right as expecte ...

Interactive radio button that only registers the most recent click

Homepage.jsx const Homepage = () => { const [categories, setCategories] = useState([]) const [products, setProducts] = useState([]) const [selected, setSelected] = useState("all") const getAllCategories = async() => { try{ ...

Updating the state of a React Component using data from 2 input fields

I am facing an issue with two input fields of type "file" in a React component. My goal is to load a JSON file into each input field, save the data from both files into separate variables, and update the state of the component. However, I have noticed that ...

Securing page access with a straightforward password protection using Flask

Looking for a straightforward way to add password protection to a Flask app site. I've explored options like flask_login, but they seem overly complex for my needs. I don't need high security or login sessions - just something like: "enter passw ...

Extracting Json data with Jquery

My JSON data format is as follows - I've been struggling to find a way to retrieve the photo reference value. Can anyone help me with this? { "debug_info" : [], "html_attributions" : [ "Listings by \u003ca href=\"http://www.yellowpages. ...

Rendering a custom Vue 3 component as a string and then passing it to another component as a prop

Hey there coding mates! Currently diving into Vue 3 and the composition API with setup. I've been crafting a custom "Table" component to display... well, tables. It requires a prop named "data", which is an array of objects (representing rows) conta ...

Is it possible to disable the timeout for a single call using Axios?

I have set up an axios client instance in my application like this: const backendClient = axios.create({ baseURL: window['getConfig']?.url?.backend, httpsAgent: new https.Agent({ rejectUnauthorized: false }), timeout: window['getConfig ...

What is the best way to extract the artist's name from this JSON data structure?

Here is a lengthy JSON object that I am working with. I need to extract the name of the artists from it, specifically under tracks -> items -> album -> artists -> name. Despite my efforts, I am unable to retrieve the artist name using the code below. Take ...

Setting up Visual Studio Code for debugging HTML and JavaScript code

Struggling to troubleshoot some HTML/JavaScript using VSCode. After installing the Chrome debugger extension and configuring the launch.json as follows: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of ex ...

When querying a table for JSON_VALUE, it often returns null instead of the expected value

JSON data is stored in a column called 'DataJson' within a table [{ "KickOffDate": "1-Jan-2019", "TeamSize": "11", "ClientEngineer": "Sagar", "WaitingPeriod": "16.5" }] A query is performed to extract specific values from the JS ...

The React Bit Dev module is showing a 404 error

Attempting to incorporate the semantic-ui-react table reusable component from the Bit.dev community into my application. The link I am using is: To add this component to your application, use: npm i @bit/semantic-org.semantic-ui-react.table However, when ...

Applying a consistent script with varying inputs on the same HTML page

Is it possible to create a JavaScript code that can be used across different sections of an HTML document? The goal is for the script to fetch data such as title, runtime, and plot from a specific URL request and insert this information into the appropriat ...

Is there a way to retrieve the row and parent width from a Bootstrap and Aurelia application?

Is there a way to determine the exact width of a bootstrap grid row or grid container in pixels using Aurelia? I attempted to find this information on the bootstrap website, but I am still unsure as there are multiple width dimensions such as col-xs, colm ...

Generate a dynamic form in Flutter for submitting new data in JSON format

One of my current tasks involves building a class to handle the consumption of REST data from a web service in JSON format. The class structure is as follows: class BuildingSiteVisits { int? id; String? name; Float? lat; Float? long; BuildingSiteV ...

Trouble with Swiper carousel loading new slides

Currently, I am working on a project using Cordova and jQuery. I have implemented the Swiper library by idangero for handling slides. The problem arises when I add new slides and try to display them. Here is the relevant jQuery code snippet: if(row.pict ...

An Error with jQuery Autocomplete: "Callback is not Defined"

I am currently working on a jQuery script that involves autocomplete and selecting the correct value on the client side. Here is my functional code without the selected value (it displays all username available in my JSON): $(function() { $( "#us ...

How can Vue listen for a Vuex commit?

Is there a method to detect when a Vuex commit occurs without having to monitor specific property changes associated with the commit? Simply knowing if a commit has taken place? I am working on a Filter component that I plan to include in an NPM package. ...