如何将数据(json)传递给vue实例 [英] How to pass data(json) to vue instance

查看:531
本文介绍了如何将数据(json)传递给vue实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Vue实例,并希望在没有HTTP请求的情况下将json从后端传递到vue,因为它始终是相同的。

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.

我尝试过这样做道具,但它不起作用...
在DOM中它看起来像< div id =my-componentprices =[object Object]>
Vue调试工具将图像显示为空字符串,并在控制台 undefined

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> 

其中 $ price json编码数组。

where $prices json encoded array.

推荐答案

您的解决方案几乎就在那里,但您不需要支柱,而是使用数据属性并通过方法分配JSON :

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>

您只需将Laravel数据分配给setJson方法有效负载,即

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

:json="setJson({{ $prices }})

这篇关于如何将数据(json)传递给vue实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆