How to pass data (json) to vue instance

I have a simple Vue instance and you want to pass json from the backend to vue without an HTTP request, because it is always the same.

I tried to do this with the help of props, but it does not work ... In the DOM, it looks like <div id="my-component" prices="[object Object]"> The Vue debug tool will show me the image as an empty string, and in undefined consoles

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

where $prices json encoded array.

+5
source share
2 answers

Your solution was almost there, but you do not need support, rather use the data attribute and assign JSON using the 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> 

You simply assign your Laravel data to the utility methods of the setJson method, i.e.

 :json="setJson({{ $prices }}) 
+8
source

I do not know if there is a Laravel helper for this, but I will present a general approach.

One option is to store JSON data in a global variable and load the page, and then use it in js files.

Basically you need to generate some html similar to:

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

Then from javascript you can access the variable myApp.userData and use it when initializing the Vue component.

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

Here is an example:

 new Vue({ el: '#app', data: { userData: myApp.userData } }); 
 <script> window.myApp = window.myApp || {}; window.myApp.userData = { "firstName": "John", "lastName": "Doe" }; </script> <div id="app"> Hello {{userData.firstName}} </div> <script src="https://unpkg.com/vue/dist/vue.js"></script> 
+3
source

Source: https://habr.com/ru/post/1260710/


All Articles