使用props将PHP数组传递到Vue组件

wea*_*dan 6 php arrays json laravel vue.js

  • 使用一些Vue组件构建Laravel应用程序
  • 想要使用props将PHP数组传递到Vue组件上

这是一个这样的PHP数组的例子:

["Foo" => 100, "Bar" => 50]

大.这是我尝试将它们传递到Chart组件:

<Chart points="{!! json_encode($points) !!}"></Chart>

这看起来很好,但是在使用时,$points数组中的字符串(Foo和Bar)用"(双引号)"封装json_encode().这意味着只要第一个字符串出现在数组中,浏览器就会认为"是关闭points属性的" .

以下是您在浏览器中看到的内容:

<Chart points="{">Foo":100,"Bar":50}"</Chart>

我该怎么做?我一直在努力奋斗几个小时,我无法绕过它.

  • 不能使用"(双引号)",因为浏览器会将其解释为属性的结束引用并弄乱HTML
  • 不能使用'(单引号),因为那是无效的JSON(并且json_encode不支持它)

小智 8

虽然阅读以前的答案这花了我一段时间才能开始工作。所以,以下是 Laravel 5.5 和 VueJs 2.5 对我有用的方法:

  1. 将您的 PHP 数组转换为 JSON 序列化字符串。

    对于 PHP 数组,请参阅json_encode
    对于Eloquent集合,请参阅Eloquent方法toJson
    为了进一步参考,我们称这个新的 JSON 字符串$arrayAsJSON

  2. 在您的视图(或 Blade 模板)中:

    <some-vue-component :componentProperty="{{ $arrayAsJSON }}"></some-vue-component>
    
    Run Code Online (Sandbox Code Playgroud)
  3. Vue 组件:

    <template></template>
    
    <script>
      export default {
    
        props: ['componentProperty'],
    
        mounted() {
            console.log('some-vue-component mounted.');
            console.log(this.componentProperty)
        },
      }
    </script>
    
    Run Code Online (Sandbox Code Playgroud)


Igo*_* Q. 6

<Chart points='{!! json_encode($points) !!}'></Chart>
Run Code Online (Sandbox Code Playgroud)

只需使用单引号即可。