Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data(json) to vue instance

I have a simple Vue instance and want to pass json from the backend to vue without HTTP request because it's always the same.

I've tried do this with props, but it doesn't work... In DOM it's looks like <div id="my-component" prices="[object Object]"> Vue debug tool show me image as an empty string, and in console 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 json encoded array.

like image 980
xAoc Avatar asked Dec 02 '16 13:12

xAoc


1 Answers

Your solution was nearly there but you don't need a prop, rather use a data attribute and assign the JSON via 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>

You would just assign your Laravel data to the setJson methods payload, i.e.

:json="setJson({{ $prices }})
like image 82
GuyC Avatar answered Oct 10 '22 00:10

GuyC