Home » Php » Pass php variable to vue component instance

Pass php variable to vue component instance

Posted by: admin November 30, 2017 Leave a comment

Questions:

How can I pass a value of a variable to a vue component?

In my example, i have an inline template client-details, i get this view from laravel so now i want to pass the id which comes with the url /client/1 to my vue instance.

My component, which is loaded by Laravel, looks like:

<client-details inline-template>
    <div id="client-details" class="">
          My HTML stuff
    </div>
</client-details>

and mounted by:

Vue.component('client-details', {
    data(){
        return {
            clientId: null
        }
    },
);

I already tried like

:clientId="{{ $client->id }"

but it does not work.

Answers:

You have to use Vue’s props to be able to pass attributes to Vue’s components through markup. Take a look at the following example:

<client-details inline-template client-id="{{ $client->id }}">
    <div id="client-details" class="">
          My HTML stuff
    </div>
</client-details>

In your Vue component:

Vue.component('client-details', {
    props: [
        {
            name: 'clientId',
            default:0,
        }
    ]
});

Now in other parts of your Vue component, you can access this value as this.clientId.

Please note that in HTML we write attribute name in kebab-case but in Vue side we write it in camelCase. More info in official docs here.

Questions:
Answers:

I just did this and it’s working great for me. Using Laravel 5.4 and Vue 2.x.

In my component, declare a property (props) for the object:

props: ['currentUser'],

On my blade page where the component is instantiated:

<my-component v-bind:current-user='{!! Auth::user()->toJson() !!}'></my-component>

Note that in the component, I am using camelCase for currentUser, but because html is case-insensitive, you have to use kebab-case (thus, the ‘current-user’).

Also note, if you use blade syntax {{ }} then the data between is run through php htmlspecialchars. if you want unencoded data (which in this case you would), then use {!! !!}