【问题标题】:Laravel + Vue - Pass multidimensional PHP array to vue componentLaravel + Vue - 将多维 PHP 数组传递给 vue 组件
【发布时间】:2021-11-06 17:59:08
【问题描述】:

config/variables.php文件中,我已经将以下对象定义为一个多维数组:

<?php

return [
    [
        'name' => 'test1',
        'surname' => 'test1'
    ],
    [
        'name' => 'test2',
        'surname' => 'tes2'
    ],
    [
        'name' => 'tes3',
        'surname' => 'test3'
    ]
];

我想在 Vue 组件中使用这些数据,例如这样:

<template>
    <div>
        <div>Items:</div>
        <div v-for="i of items">
            {{ i.name }} {{ i.surname }}
        </div>
    </div>
</template>

<script>
export default {
    name: "Test",
    props: {
        items: []
    }
}
</script>

我将组件和数据放在一个刀片模板中,其中包含以下内容:

<div>Begin of test</div>
<Test :items="@json(Config::get('variables'))"></Test>
<div>End of test</div>

我希望 Laravel 将数据传递给组件,然后呈现一个简单的页面,其中包含带有提供数据的 div。我在浏览器中实际看到的是这样的:

<div>Begin of test</div>
":"test1","surname":"test1"},{"name":"test2","surname":"tes2"},{"name":"tes3","surname":"test3"}]"="">
<div>End of test</div>

一方面,数据似乎在此过程中出现乱码。此外,组件的&lt;div&gt;Items:&lt;/div&gt; 根本不会出现。因此,@json 调用似乎以某种方式破坏了整个组件。使用 {!! json_encode(Config::get('variables')) !!} 的行为相同。当我将配置值直接输出到像 &lt;div&gt;@json(Config::get('variables'))&lt;/div&gt; 这样的 div 中时,完整的数组会干净地打印为 JSON。

为什么会发生这种情况,我该如何解决?

【问题讨论】:

    标签: javascript php json laravel vue.js


    【解决方案1】:

    你快到了!
    您刚刚忘记在刀片视图的元素中转义 PHP。
    应该是;

    <div>Begin of test</div>
    <Test :items="{{ json_encode(Config::get('variables')) }}"></Test>
    <div>End of test</div>
    

    如果你想使用@json 标签,你需要去掉双引号。 示例;

    <div>Begin of test</div>
    <Test :items=@json(Config::get('variables'))></Test>
    <div>End of test</div>
    

    我不是 JS 专家,但我认为这是因为当传递给 :items(v-bind 的快捷方式)时,它被视为 JavaScript 表达式。

    【讨论】:

    • 我惊呆了。以为我什么都试过了。但是为什么它在常规 div 中使用 @json 呢?谢谢,这解决了。我会尽快接受。
    • @herhuf 你可以使用@json 标签,回答更新
    【解决方案2】:

    更新你的 variables.php

    <?php
    
    $return = array(
      array(
       'name' => 'test1',
       'surname' => 'test1'
      ),
      array(
      'name' => 'test2',
       'surname' => 'tes2'
      ),
      array(
      'name' => 'tes3',
      'surname' => 'test3'
      )
    );
    
    echo json_encode($return);

    【讨论】:

      猜你喜欢
      • 2019-10-07
      • 2018-06-20
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      • 2021-01-18
      • 2017-12-02
      相关资源
      最近更新 更多