且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Laravel刀片中将PHP变量传递给Vue组件实例?

更新时间:2022-10-27 23:15:42

您必须使用Vue的props才能通过标记将属性传递给Vue的组件.看下面的例子:

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

在您的Vue组件中:

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

现在在Vue组件的其他部分,您可以将其作为this.clientId来访问.

问题详细信息

请注意,在HTML中,我们以 kebab-case 来写属性名称,而在Vue方面,我们以 camelCase 来写属性名称. 此处的官方文档中的更多信息.

此外,您在:clientId="{{ $client->id }}"中使用Vue的v-bind速记,这意味着Vue会将双引号内的任何内容作为JavaScript表达式处理,因此在这种情况下也可能会出错.相反,您应该使用此格式clientId="{{ $client->id }}而不使用冒号.

How can I pass a value of a PHP variable to a Vue component in Laravel blade files?

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.

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.

Issue Details

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.

Also, you are using Vue's v-bind shorthand in :clientId="{{ $client->id }}" which means that Vue will deal anything inside double quotes as a JavaScript expression, therefore you may get errors in that case as well. Instead, you should use this format clientId="{{ $client->id }} without a colon.