Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass PHP array onto Vue component using props

  • Building a Laravel app with a few Vue components
  • Want to pass a PHP array onto a Vue component using props

Here's an example of such PHP array:

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

Great. Here's my attempt at passing them onto the Chart component:

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

This looks fine, but the strings (Foo and Bar) inside the $points array get encapsulated with " (double quotes) when using json_encode(). This means that whenever the 1st string appears in the array, the browser thinks that the " is meant to close the points attribute.

Here's what you get to see in the browser:

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

How do I go about this? I have been struggling with this for hours now, and I can't wrap my head around it.

  • Can't use " (double quotes) since the browser interprets it as the closing quote for an attribute and messes up the HTML
  • Can't use ' (single quotes) since that's invalid JSON (and json_encode doesn't support it)
like image 973
weakdan Avatar asked Nov 09 '17 23:11

weakdan


2 Answers

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

Just use singular quotes.

like image 79
Igor Q. Avatar answered Sep 23 '22 14:09

Igor Q.


Although reading previous answers this took me a while to get working. So, here's what works for me with Laravel 5.5 and VueJs 2.5:

  1. Convert your PHP array to a JSON serialized string.

    For PHP arrays see json_encode.
    For Eloquent collections see the Eloquent method toJson.
    For further reference we call this new JSON string $arrayAsJSON.

  2. In your view (or Blade template):

    <some-vue-component :componentProperty="{{ $arrayAsJSON }}"></some-vue-component>
    
  3. The Vue Component:

    <template></template>
    
    <script>
      export default {
    
        props: ['componentProperty'],
    
        mounted() {
            console.log('some-vue-component mounted.');
            console.log(this.componentProperty)
        },
      }
    </script>
    
like image 25
Didi Avatar answered Sep 20 '22 14:09

Didi