How to pass data(json) to vue instance

2019-02-09 21:00发布

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.

2条回答
▲ chillily
2楼-- · 2019-02-09 21:16

I don't know if there is any Laravel helper for this but I will present a generic approach.

One option would be to store you JSON data in a global variable and the page loads and then use it in your 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 should be able to access the myApp.userData variable 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楼-- · 2019-02-09 21:27

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 }})
查看更多
登录 后发表回答