如何在Laravel刀片中将PHP变量传递给Vue组件实例? [英] How to pass a PHP variable to Vue component instance in Laravel blade?
问题描述
如何将PHP变量的值传递给Laravel刀片文件中的Vue组件?
在我的示例中,我有一个内联模板client-details,我从Laravel
获取此视图,所以现在我想将URL /client/1
附带的id
传递给我的Vue
实例. /p>
由Laravel
加载的我的组件看起来像:
<client-details inline-template>
<div id="client-details" class="">
My HTML stuff
</div>
</client-details>
并通过以下方式安装:
Vue.component('client-details', {
data(){
return {
clientId: null
}
},
);
我已经尝试过
:clientId="{{ $client->id }"
但它不起作用.
您必须使用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.
这篇关于如何在Laravel刀片中将PHP变量传递给Vue组件实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!