Sending JSON data to Vue using HTML attributesHere's a guide on how you can pass JSON

How can I successfully pass JSON data via an HTML attribute in Vue.js?


<div id="app" data-number="2" data-json="{"name":"John", "age":30, "car":null}"></div>

In my main.js file

new Vue({
    el: `#app`,
    render: h => h(App,{
      props:{
        myNumber: this.dataset.number,
        myData: this.dataset.json
      }
    })
  })

When attempting to access the JSON data with console.log(this.dataset.number), the output is correct (2). However, when trying to access myData, only a single curly brace ({) seems to be returned. How can I properly pass JSON data to the Vue instance?

Answer №1

The first step involves binding data,

<div id="app" data-number="2" :data-json="{"name":"John", "age":30, "car":null}"></div>

Alternatively, you can also use

<div id="app" data-number="2" v-bind:data-json="{"name":"John", "age":30, "car":null}"></div>

The second step is to convert the JSON data into a string. This can be done using JSON.stringify() before passing it as a prop. Then, within the component, you can parse the string back into JSON using JSON.parse(),

new Vue({
    el: `#app`,
    render: h => h(App,{
      props:{
        myNumber: JSON.stringify(this.dataset.number),
        myData: JSON.stringify(this.dataset.json)
      }
    })
  })

Answer №2

The issue lies with the quotes in this code snippet. It would be more efficient to properly bind the variables as mentioned by @Batuhan.

<div id="app" data-number="2" data-json="{'name':'John', 'age':30, 'car':null}"></div>

// or

<div id="app" data-number="2" data-json='{"name":"John", "age":30, "car":null}'></div>

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

Automatically open Bootstrap dropdown upon loading the page

Displayed below is my dropdown menu styled using bootstrap: <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" id="posuvnik">15min <strong class="caret"></strong></a> <ul class="dropd ...

Ensuring that undefined is not present before making an API request is crucial in the componentWillMount lifecycle

When I have a component that triggers methods depending on asynchronous API requests, I check certain props using componentWillmount. If a specific prop is true, I trigger a function; otherwise, I do not. The issue arises when the prop is initially undef ...

Receiving a 200 response code, however the controller's store() method is not being accessed

Recently, I made the decision to switch from using a form in a blade file to a Vue-based form that utilizes Axios for posting data. After making these changes, I encountered an issue where I receive a 200 response, but my controller's store() method i ...

Is there a way to determine if a website is utilizing javascript?

Currently, I am in the process of developing a web scraping tool using beautifulsoup. Some of the websites I am targeting contain JavaScript elements that prevent me from using urllib3 efficiently. As a workaround, I have incorporated selenium into my sc ...

How can I make TypeScript mimic the ability of JavaScript object wrappers to determine whether a primitive value has a particular "property"?

When using XMLValidator, the return value of .validate function can be either true or ValidationError, but this may not be entirely accurate (please refer to my update). The ValidationError object includes an err property. validate( xmlData: string, opti ...

PhpStorm's file relocation feature now includes adding "/types" to the Vuex import statement in Vue.js files

Dealing with Vue.js single file components in PhpStorm has presented a challenge for me. Whenever I relocate a component file to a different directory, PhpStorm somehow appends "/type" to the end of every vuex import statement, causing them to malfunction ...

Issues with Skrollr JS on mobile device causing scrolling problem

Currently facing an issue with Skrollr js. It is functioning perfectly in web browsers and mobile devices. However, there seems to be a problem when tapping on a menu or scrolling down arrow as it does not initiate scrolling. Assistance would be greatly ...

What is the best way to arrange an array or display it accurately?

Guys, here's a challenge for you: extract the values from this JSON data: [[name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category]] Check out my JavaScript code: $(function(){ $('i ...

Utilizing jQuery to correspond with CSS media queries

Continuing from my previous question about an automatic jQuery image slider, you can refer to it here. I have made some changes in my CSS using media queries and I am trying to incorporate them into my JavaScript code using an 'if / else if' sta ...

Maximizing efficiency in Office Automation programming by choosing individuals proficient in Javascript and PHP

I am seeking a solution where upon selecting a department checkbox, the employees belonging to that department will be displayed in the second div. This way, I can easily select an employee and have their information displayed in a separate section. I al ...

Retrieve the parent document for every item within a Firebase collection group

Transitioning from an SQL background to document storage, I am currently navigating through a Firebase database structure that looks like this: John (doc) Restaurant Reviews (collection) Review 1 (doc) Review 2 (doc) Paul (doc) Restaurant Reviews ...

Does Apollo in Vue take care of caching previously visited pages, or will I need to store them in my own store?

I'm currently developing an app using apollo and vue (nuxt) and I'm curious about whether I need to save already fetched pages in my store for optimal speed when a user revisits a page. Currently, I have a section where I retrieve some apollo qu ...

Extracting data from a JSON file with the help of Node.js

I've recently delved into node.js and find myself in a bit of a pickle. I have a json file called keyValue.json that looks something like this [ { "key": "key1", "value": "value1" }, { "key": "key2", "value": "value2" } ] I ...

What type of information is typically stored in the idsrv cookie on IdentityServer4?

Looking to implement IdentityServer for the authentication aspect of my single page application. After noticing the generation of certain cookies, I delved into the documentation to learn more about the idsrv cookie. From what I gathered, besides the authe ...

Use javascript/ajax to submit the form on a separate page

I'm trying to use ajax to submit a form on another page, but my code doesn't seem to be working. Here is what I have: Send(); function Send() { var abc = document.getElementsByClassName("main"); for (var i = 0; i < abc.length; i++) { var ...

How to bring in images from a local source in a React.js file

I've been looking into relative paths and absolute paths, but I'm having trouble importing local images correctly. My main objective is to create a React slideshow using these images. Why does it keep trying to find the images in the "components" ...

What's causing my React app's slideshow to malfunction?

Struggling with styling my React app after importing w3.css and attempting to create a slideshow with 3 images in the same directory as the component being rendered. As someone new to React and web development, I'm facing challenges in getting the des ...

Restricting the type of user input in HTML forms

Requirements: Input must be a whole number between 2 and 99, inclusive. Current Solution: <input required type="number" min="2" max="99" oninput="this.value = Math.abs(this.value)" maxLength="2" matInp ...

Reactive forms in Angular now support changing focus when the Enter key is pressed

I have successfully created a table and a button that generates dynamic rows with inputs inside the table. One issue I'm facing is that when I press enter in the first input, a new row is created (which works), but I can't seem to focus on the ne ...

It appears that there may be an unhandled promise rejection for a request with ID 0, specifically a typeerror indicating that the body

import React from 'react'; import { FlatList, ActivityIndicator, Text, View } from 'react-native'; export default class DataFetcher extends React.Component { constructor(props){ super(props); this.state ={ isLoading: true} ...