The process of sending JSON data to a Vue instance

I am facing an issue with my Vue instance where I need to pass JSON data from the backend without using HTTP requests because the data is constant.

I attempted to achieve this using props, but encountered some challenges... In the DOM, it appears as

<div id="my-component" prices="[object Object]">
The Vue debug tool shows the image as an empty string, and the console displays undefined

<div id="my-component" :prices="{{ $prices }}">
</div>

<script>
        new Vue({
            el: '#my-component',
            props: ['prices'],
            mounted: function() {
               console.log(this.image);
           },
       });
</script> 

where $prices represents a json-encoded array.

Answer №1

Your solution was on the right track, but instead of using a prop, it's better to utilize a data attribute and assign the JSON through a method:

new Vue({
    el: '#app',
    data: {
        json: {},
    },
    methods: {
        setJson (payload) {
            this.json = payload
        },
    }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app" :json="setJson({ foo: 'bar' })">
    <pre>{{ json }}</pre>
</div>

To pass your Laravel data to the setJson method, you can do the following:

:json="setJson({{ $prices }})

Answer №2

Is there a specific Laravel helper for this task? I am not aware of one, but I can provide a general solution.

One approach is to save your JSON data in a global variable when the page loads and then utilize it in your JavaScript files.

The basic idea is to create HTML code similar to this:

<script>
window.myApp = window.myApp || {};
window.myApp.userData = { "firstName": "Jane", "lastName": "Smith" };
</script>

Then, you can access the myApp.userData variable from JavaScript and use it when setting up the Vue component.

new Vue({
    el: '#app',
    data: {
        userData: myApp.userData
    }
});

Below is an example:

new Vue({
  el: '#app',
  data: {
    userData: myApp.userData
  }
});
<script>
  window.myApp = window.myApp || {};
  window.myApp.userData = { "firstName": "Jane", "lastName": "Smith" };
</script>


<div id="app">
  Hello {{userData.firstName}}
</div>

<script src="https://unpkg.com/vue/dist/vue.js"></script>

Answer №3

Initially, I upvoted the provided answer, but later realized that I needed to change my vote (unfortunately, I lack the necessary reputation to do so).

It is crucial not to set data in this manner, as it can lead to an error message such as:

[Vue warn]: You may have an infinite update loop in a component render function

If any components rely on data being set like this (through watching or rendering), it will result in an endless loop.

When utilizing this approach:

  1. You are setting the data within the render function (in the template)
  2. If something triggers a re-render, the data will be set again
  3. Any component using this data will need to re-render, potentially causing a re-render of the main Vue instance

This sequence of events creates the infinite loop.

An explanation by LinusBorg can be found here.

Answer №4

Although this post is dated, here is my approach (inspired by my experience with Symfony 4 + VueJS):

<div id="my-component" prices-data="{{ json($prices) }}">
</div>

<script>
        new Vue({
            el: '#my-component',
            props: ['pricesData'],
            data: {
               prices: null,
            },
            mounted: function() {
               this.prices = JSON.parse(this.pricesData);
           },
       });
</script> 

This assumes that $prices is a blade variable.

Note: I utilized @json() when $prices can be encoded using json_encode() for simple objects (blade's underlying function). For complex objects, consider utilizing JMS Serializer with @MaxDepth annotations to handle complex structures.

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

The table cells are not displaying properly within their respective table rows

JSON Layout: {"rows": [ {"row":[ {"cells": [ {"data": "Edit"}, {"data": "030194"}, ]} ]}, {"row":[ {"cells": [ {"data": "Add"}, {"data": "030194"}, ]} ]}, {"row":[ {"cells": [ {"data": "Delete ...

Issue with marker functionality on Google Maps JavaScript API when conditions are not functioning correctly

I am currently working on plotting different markers on Google Maps by extracting data from a CSV file. I have incorporated the parsecsv-0.4.3-beta library to read the CSV file, and everything is functioning smoothly except for when I compare two fields to ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

Exploring ways to access an element's background color through JavaScript

Is there a way to access an element's CSS properties that are set by a class name in JavaScript? In the case of the first div element, I have applied a "red" class which sets its background color to red. However, when I try to access the div's b ...

TypeScript raises an issue with a Vue component property that has been defined using vue-property-decorator

I have a Vue component with a property defined using a decorator: import { Component, Vue } from "vue-property-decorator" @Component({ props: { myId: String, }, }) class TestProp extends Vue { myFuncti ...

The SrollToTop function is ineffective when used with a component in Ionic 6/Angular

Recently, I implemented a fabbutton feature that allows users to scroll to the top of a page with just one click. Initially, I tested this functionality without using it as a component, and everything worked perfectly. However, now I want to turn this fabb ...

Ways to deliver JSON Array in ASP.NET Web API C#

I need to display a JSON array in the following format on a web browser: { "RainfallAreaAVG": [ { "AreaBbsID": "18", "DistCount": "1", "SubDistCount": "2", "Amount": "14", "Hail": "14", "ArealDetails ...

What is the best way to convert $('input[type=text]') into vanilla JavaScript?

How can I change this to plain JavaScript? I've been struggling to find a solution, any pointers? ...

Retrieving data from Immediately Invoked Function Expressions

I've been working with a closure that looks like this: var Container = (function () { var variable; var changeVariable = function () { variable = 5; }; return { variable: variable, changeVariable: changeVariable }; ...

Checking phone number on a React.js form

I am currently working on a front-end application and need to implement form validation. I am relatively new to ReactJS and learning as I go along in the development process. One of the input fields requires a phone number, which should only accept number ...

What is the method in Vue.js for receiving notifications when a property's value is accessed?

Currently, I am working on a project using Vue.js and facing a challenge with dependencies. In my data object, there is a boolean property that I need to track whenever it is accessed or used so that I can make changes to other properties before the boolea ...

Using Highstock for Dynamic Data Visualization in Web Applications

Looking to create a chart using data from a MySQL database that includes timestamps and temperature readings. The timestamp format is '2015-06-11 22:45:59' and the temperature is an integer value. Unsure if the conversion of the timestamp to Java ...

Error 400: The onCreate Trigger function for Cloud functions is experiencing issues with HTTP requests due to errors in the request

I am encountering an issue when attempting to add a trigger for Firestore OnCreate, as the deployment fails with HTTP Error: 400 stating that the request has errors. Essentially, my goal is to write to a new document if a record is created in a different ...

Exploring the possibilities of leveraging Vuex map helpers through the Composition API

Can you assist me in using the Composition API in Vue2 to access mapState? I am looking to monitor state changes and would like to use it within the setup function as well, not just in the return statement. Your help is much appreciated. ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...

Ensuring that a service is completely initialized before Angular injects it into the system

When Angular starts, my service fetches documents and stores them in a Map<string, Document>. I use the HttpClient to retrieve these documents. Is there a way to postpone the creation of the service until all the documents have been fetched? In ot ...

Prepared SQL Statement in NodeJS for MSSQL using WHERE IN clause

I'm using the sql npm package in my Node.js project. Currently, I have an array of product SKUs like this: var skus = ['product1', 'product2', 'product3']; The SQL query stored in a file looks like this: SELECT * FROM ...

A guide on identifying the data type of a value entered into an HTML table using JavaScript

Currently, I am tackling a contenteditable HTML table challenge. My goal is to enforce the insertion of only numeric values while alerting the user if they attempt to input strings or non-numeric characters. Can anyone provide guidance on how to achieve th ...

"Using jQuery to enable ajax autocomplete feature with the ability to populate the same

I am encountering a problem with jQuery autocomplete. It works perfectly fine with one textbox, but when I create multiple textboxes using jQuery with the same ID, it only works for the first textbox and not the others. My question is how can I create mult ...

conversion of text to number using JavaScript

After pulling values from an XML file using JavaScript, I face the challenge of converting a string to an integer in order to perform calculations. To extract data from the XML file, I use the following snippet: var pop = JSON.stringify(feature.attribute ...