如何将 PHP 变量传递给 Laravel Blade 中的 Vue 组件实例? [英] How to pass a PHP variable to Vue component instance in Laravel blade?

查看:37
本文介绍了如何将 PHP 变量传递给 Laravel Blade 中的 Vue 组件实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 PHP 变量的值传递给 Laravel 刀片文件中的 Vue 组件?

在我的示例中,我有一个内联模板客户端详细信息,我从 Laravel 获得此视图,所以现在我想传递 url id 随附的 idcode>/client/1 到我的 Vue 实例.

我的组件由 Laravel 加载,如下所示:

<div id="client-details" class="">我的 HTML 内容

</客户详细信息>

并安装于:

Vue.component('client-details', {数据(){返回 {客户端 ID:空}},);

我已经试过了

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

但它不起作用.

解决方案

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

<div id="client-details" class="">我的 HTML 内容

</客户详细信息>

在您的 Vue 组件中:

Vue.component('client-details', {道具: [{名称: 'clientId',默认值: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.

这篇关于如何将 PHP 变量传递给 Laravel Blade 中的 Vue 组件实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆