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

Navigating an Array of Objects is not functioning properly within React

In my React App, I am facing an issue with populating a key identifier. Currently, the key is based on the Object.name property, but this is not ideal as it could lead to duplications and trigger errors in React. The server does not provide a unique key ei ...

What steps can be taken to address an unusual conflict arising between a form post and an ajax post

One web page features the use of ajax for editing existing values. This is achieved by utilizing jQuery Inline Edit to post new data, update records, and return with success. The process works well initially. Subsequently, I implemented the functionality ...

Regain focus after selecting a date with Bootstrap datepicker

When initializing a bootstrap datepicker from eternicode with the parameter autoclose: true, there are two undesired behaviors that occur: After closing the picker, tabbing into the next field causes you to start at the beginning of the document again, w ...

Can you suggest a simpler approach to implementing this function?

Greetings to all who are perusing this message. I have devised a technique for retrieving today's date along with the current time. If the deadline value in the database is null, it will fetch the current datetime and format it correctly. Otherwise, ...

increasing the size of an array in react javascript

componentWillMount(){ this.adjustOrder(); } componentDidMount(){} adjustOrder(){ var reorderedArray = []; this.state.reservation1.length = 9; for (var i = 0; i < this.state.reservation1.length; i++) { if(this.state.reservation1[i]){ r ...

Creating a specific quantity of divs with JavaScript

For the past few hours, I've been working hard to solve this problem that has really left me stumped. As far as I can tell, everything is correct. The create function is supposed to generate a certain number of divs specified by the user in an input b ...

Node.js is great at hosting HTML files, but struggles when it comes to loading script files within those pages

Recently, I’ve been working on creating a simple login page using a mongoDB database along with Node.js and express. Since I'm still new to Node.js, I'm facing an issue that seems more complicated than it actually is. The main problem I’m en ...

contrasting the application of logic in Rails controllers versus JavaScript within the .js.erb files

When dealing with a large "data" active record object that needs to be filtered based on user interactions on a page, the question arises about where to place the data-filtering logic. Currently, the filtering is done in the rails controller action, simpli ...

Having issues with deserializing boolean data types from a JSON file in Python

I am working with a json file and facing an issue where the content is not properly decoding the string "false" to False in Python 2.7.6 (not yet tested in Python3). { "qps": 30, "force_push": "false" } Here is the code snippet that is failing to dec ...

Is there a way to transform a tabulated tree into JSON using JavaScript?

I've been searching for a solution, but I have come to the conclusion that this question is quite peculiar. How can I convert the following text file using tabs for spacing: parent child child parent child grandchild grand ...

Converting a Spark DataFrame to a JSON array

Currently, I am developing a Spark Application in Java that reads data from a HiveTable and stores the output in HDFS in JSON format. I am using the HiveContext to read the hive table, which returns the DataFrame. Below is an excerpt of the code: SparkCo ...

Looking to retrieve the checkbox value from HTML in AngularJS and pass it to the controller

How can I retrieve the value of a checkbox on button submit in a controller Function? <input id="Check" type="checkbox" ng-model="CheckValue" /> ...

"Enjoying the convenience of a stationary header while browsing on your smartphone

Hey there! I'm currently facing an issue with my website's fixed horizontal nav bar when zooming in on a mobile device. After doing some research, it seems the only solution is to implement some javascript. I came across a jquery fix (see below) ...

Having issues with texturing my glb model in three.js

As a beginner in this field, I recently uploaded my model and attempted to add the necessary textures to it. const textureloader = new THREE.TextureLoader(); const material = new THREE.MeshStandardMaterial({ map: textureloader.load('./assets/texture ...

The Johnny-Five stepper initiates movement within a for-loop

I am new to using node.js and johnny-five. I want to move a stepper motor 5 times with 1000 steps each. Here is what I have tried: do 1000 Steps in cw ; console.log('ready); do 1000 steps; console.log('ready') ... It woul ...

The task "gulp js src - duplication and implementation of base" involves duplicating

My gulp task is set up to copy JavaScript files. The initial setup below did not work: gulp.src('./**/*.js', {base: '../src/main/'}) .pipe(gulp.dest('../target/dist')); After making some adjustments, the following code ...

Searching for client using mqtt.js in Angular2 with Typescript yields no results

I am facing a unique issue while trying to incorporate the mqtt.js library into Angular 2 using TypeScript. Below is my app.component.ts file: import { Component } from '@angular/core'; import * as mqtt from 'mqtt'; @Component({ sel ...

A guide on passing an array parameter using JavaScript

I need to transfer an array of ids from one page to another. I have created the $ids variable in PHP, and I am using it with jQuery like this: var ids = <?php echo json_encode($ids); ?>; jQuery(ids).each(function() { filters.push('ids[]=&a ...

Error encountered in NextJS middleware: NetworkError occurred while trying to retrieve resource

I'm currently working with a middleware setup in NextJS based on an old tutorial. The code provided in the tutorial seems to be functioning correctly, but when I implement the same code, I encounter a NetworkError. Upon further investigation, it appea ...

The event is not triggered by ng-submit

I'm struggling with submitting this form. I've checked everything, but it just won't work. This is my HTML: <html ng-app = 'myApp'> <div ng-controller="Tabs"> ... <form ng-submit="sendClicked()" &g ...