如何将 PHP 变量传递给 Laravel Blade 中的 Vue 组件实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41520258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:24:08  来源:igfitidea点击:

How to pass a PHP variable to Vue component instance in Laravel blade?

phplaravelvue.jsvuejs2

提问by mastercheef85

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

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

In my example, I have an inline template client-details, I get this view from Laravelso now I want to pass the idwhich comes with the url /client/1to my Vueinstance.

在我的示例中,我有一个内联模板客户端详细信息,我从中获得了这个视图,Laravel所以现在我想将id带有 url 的 url/client/1传递给我的Vue实例。

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

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

<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.

但它不起作用。

回答by Mustafa Ehsan Alokozay

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

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

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

In your Vue component:

在您的 Vue 组件中:

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.

现在,在 Vue 组件的其他部分,您可以将这个值作为this.clientId.

Issue Details

问题详情

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

请注意,在 HTML 中,我们将属性名称写在kebab-case 中,但在 Vue 端,我们将其写在camelCase 中此处的官方文档中的更多信息。

Also, you are using Vue's v-bindshorthand 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.

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

回答by Hawkeye64

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

我只是这样做了,它对我来说很好用。使用 Laravel 5.4 和 Vue 2.x。

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

在我的组件中,为对象声明一个属性(道具):

props: ['currentUser'],

props: ['currentUser'],

On my blade page where the component is instantiated:

在我实例化组件的刀片页面上:

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

<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').

请注意,在组件中,我使用的是驼峰命名法currentUser,但由于 html 不区分大小写,因此您必须使用 kebab-case(因此,即“当前用户”)。

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 {!! !!}

另请注意,如果您使用刀片语法,{{ }}则两者之间的数据将通过 php 运行htmlspecialchars。如果你想要未编码的数据(在这种情况下你会),然后使用{!! !!}

回答by Jonathan Whittle

For anyone who comes across this thread and is still getting errors, the answer is correctly given above by Mustafa Ehsan, but not explained. Trial and error helped me see it.

对于遇到此线程但仍然出现错误的任何人,Mustafa Ehsan 在上面给出了正确的答案,但没有解释。反复试验帮助我看到了它。

My component in newuser.blade.php

我在 newuser.blade.php 中的组件

<access-request
       firstname="{{ $newuser->firstname }}"
       lastname="{{ $newuser->lastname }}"
       accessid="{{ $newuser->id }}"
>
</access-request>

Its very important to note the binding method used. On the component above, I wrote only the name of the data binding (like React props), then registered it on the component props (see below). This is how Mustafa wrote his binding in his answer, and works fine. The other, more Vue way to pass the props is with the v-bind: or :, but you have to make sure to use both double-quotes and single-quotes:

注意使用的绑定方法非常重要。在上面的组件上,我只写了数据绑定的名称(如 React props),然后将其注册到组件 props 上(见下文)。这就是穆斯塔法在他的回答中写他的绑定的方式,并且工作正常。另一种更 Vue 传递 props 的方法是使用 v-bind: 或 :,但你必须确保同时使用双引号和单引号:

:firstname="'{{ $newuser->firstname }}'"

Without both quotes, you get Vue warnings.

如果没有两个引号,您会收到 Vue 警告。

AccessRequest.vue:

访问请求.vue:

<template>
   <div class="component">
        <h3 class="">{{ firstname }} {{ lastname }}</h3>
        <p>Access ID: {{ accessid }}</p>
        <label for="administrator">Grant Administrator Priviledges:</label>
        <input name="administrator" type="checkbox" value="True" class="mb-5"><br>
        <button type="submit" class="btn btn-success">Add</button>
        <button type="submit" class="btn btn-danger">Delete</button>
        <hr>
   </div>
</template>

<script>
  export default {
    name: "AccessRequest",
    props: ['firstname', 'lastname', 'accessid'],
  }
</script>

回答by antoineMoPa

I had to pass some server data to my Vue component, I ended up creating a $server_datavariable in the controller and passing it in a json script tag.

我不得不将一些服务器数据传递给我的 Vue 组件,我最终$server_data在控制器中创建了一个变量并将其传递到一个 json 脚本标签中。

In the controller:

在控制器中:

$server_data = json_encode([
    "some-data" => SomeObject::all()
]);

return View::make('myview', compact('server_data'));

In the template:

在模板中:

<script type="application/json" name="server-data">
    {{ $server_data }}
</script>
<!-- Inserts server data into window.server_data -->
<script>
    var json = document.getElementsByName("server-data")[0].innerHTML;
    var server_data = JSON.parse(json);
</script>

In the vue initialisation, I put a computed property:

在 vue 初始化中,我放了一个计算属性:

computed: {
    'server_data': function(){
        return window.server_data;
    }
}

Then, the data is accessible in the component template with server_data.some_object.

然后,可以在组件模板中使用server_data.some_object.

This allows to pass a lot of structured data without needing many html attributes. Another benefit is that the data is escaped by the the json encoding. This avoids potential bugs with variables that contain double quotes ("), which would mess up the dom.

这允许在不需要许多 html 属性的情况下传递大量结构化数据。另一个好处是数据被 json 编码转义。这避免了包含双引号 (") 的变量的潜在错误,这会弄乱 dom。