DEV Community

loading...

Pass PHP array onto Vue component using props

akamittal
Just a simple developer
Originally published at fix.code-error.com ・1 min read
  1. Building a Laravel app with a few Vue components
  2. Want to pass a PHP array onto a Vue component using props

Here’s an example of such PHP array:

["Foo" => 100, "Bar" => 50]
Enter fullscreen mode Exit fullscreen mode

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

<Chart points="{!! json_encode($points) !!}"></Chart>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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)

Solution

<Chart points='{!! json_encode($points) !!}'></Chart>
Enter fullscreen mode Exit fullscreen mode

Just use singular quotes.

Discussion (1)

Collapse
ibonkonesa profile image
Ibon

Why not calling API HTTP from Vue to Laravel and avoid this?