最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass data(json) to vue instance - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Dec 2, 2016 at 14:07 xAoc asked Dec 2, 2016 at 13:35 xAocxAoc 3,5883 gold badges24 silver badges36 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 18

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 }})

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>

I have upvoted this answer first, but I have to change my vote (can't do it actually not enough reputation...).

Please do not set the data this way, because it will trigger an error like this: [Vue warn]: You may have an infinite update loop in a component render function

If anything will use the data you set this way (watch, render components based on it) you will have an infinite loop.

When you use this method:

  1. you set the data in the render function (in the template)
  2. if something triggers a re-render, the data will be set again
  3. anything using this data will have to re-render, which may cause a re-render on the main vue instance

This will cause the infinite loop.

LinusBorg have an explanation here.

While this op is old, here is how I would do it (inspired by how I do it in 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 is obviously assuming that $prices is a blade variable.

Note: I used @json() above when $prices is a simple object that can be encoded with json_encode() (underlying function being used when you call blade json function. If however the object is complex, consider using JMS Serializer with @MaxDepth annotations if objects become too complex.

发布评论

评论列表(0)

  1. 暂无评论