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. Commented Jul 14, 2020 at 16:07
  • You don't need this. in :href="this.homeRoute" 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>
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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
@RobertYoung it's a string in PHP but in JavaScript it should be interpreted as an object.
@fromvega thankyou. I have just tried this and it works. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.