0

I am trying to pass a php object into a Vue JS component and use its keys in order to access its values within the component.

The syntax that I am using to parse the php object within the vue component must be incorrect because at the moment the object values within the vue html are showing up as undefined undefined.

I wondered if anyone had any useful suggestions?

PHP blade file

    @foreach($clients as $client)
    
        <client client='{!! json_encode($client) !!}' home-route="{{ route('clients.show', $client->id) }}"></client>
    @endforeach

vue component


    <template>
        <li :data-clientID="client.id"><a :href="this.homeRoute">{{ client.first_name + ' ' + client.last_name }}</a>
            <span class="delete_x" data-toggle="modal" data-target="#delete_modal" :data-model="client.id">x</span>        
        </li>
    </template>
    
    <script>
        export default {
            name: 'client',
            props: {
                client: {
                    type: String,
                    required: true
                },
                homeRoute: {
                    type: String,
                    required: true
                }
            }
        }
    </script>

Output

enter image description here

2
  • 2
    Please show us the HTML generated.
    – lbrandao
    Commented Jul 14, 2020 at 16:07
  • You don't need this. in :href="this.homeRoute"
    – Phil
    Commented Jul 15, 2020 at 2:46

1 Answer 1

1

You defined the client prop as String instead of object. Try:

export default {
    name: 'client',
    props: {
        client: {
            type: Object,
            required: true
        },
        homeRoute: {
            type: String,
            required: true
        }
    }
}

and bind the client prop using v-bind so it's not interpreted as a string

<client
  :client='{!! json_encode($client) !!}' 
  home-route="{{ route('clients.show', $client->id) }}"
></client>
4
  • Yup. @fromvega, that's because I am using json_encode to encode it as a json string in my blade template. It isn't an object. Commented Jul 14, 2020 at 16:49
  • 1
    All this answer needs is to change the prop binding to :client (or v-bind:client) so the JSON encoded string is interpreted as an object
    – Phil
    Commented Jul 15, 2020 at 2:45
  • 1
    @RobertYoung it's a string in PHP but in JavaScript it should be interpreted as an object.
    – lbrandao
    Commented Jul 15, 2020 at 14:16
  • @fromvega thankyou. I have just tried this and it works. Thanks for your help. Commented Jul 16, 2020 at 11:50

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.