将参数参数从Laravel集合传递到Vue组件

时间:2020-09-04 18:47:30

标签: php laravel vue.js laravel-blade

在我的blade.php文件中,当转储时,我现在有一个变量$item等于:

Illuminate\Database\Eloquent\Collection {#2313 ▼
  #items: array:48 [▶]
}

然后在我的blade.php文件中,我调用一个Vue组件,并试图绑定并传递一条路线(路线应在Vue中通过其ID动态呈现一个项),看起来像:

 <my-items
   :route="{{ json_encode(route('items.show', ['id' => $item->id])) }}"
  ></my-items>

但是当我重新加载页面时,出现此错误:

Property [id] does not exist on this collection instance.

转储$ items

Illuminate\Database\Eloquent\Collection {#2371 ▼
#items: array:48 [▼
0 => App\Items {#2351 ▶}
1 => App\Items {#2350 ▶}
2 => App\Items {#2349 ▶}
3 => App\Items {#2348 ▶}
4 => App\Items {#2347 ▶}
5 => App\Items {#2346 ▶}
6 => App\Items {#2345 ▶}
7 => App\Items {#2344 ▶}
8 => App\Items {#2343 ▶}
9 => App\Items {#2342 ▶}
10 => App\Items {#2341 ▶}
11 => App\Items {#2340 ▶}
12 => App\Items {#2339 ▶}
13 => App\Items {#2338 ▶}
14 => App\Items {#2337 ▶}
15 => App\Items {#2336 ▶}
16 => App\Items {#2335 ▶}
17 => App\Items {#2334 ▶}
18 => App\Items {#2333 ▶}
19 => App\Items {#2332 ▶}
20 => App\Items {#2331 ▶}
21 => App\Items {#2330 ▶}
22 => App\Items {#2329 ▶}
23 => App\Items {#2328 ▶}
24 => App\Items {#2327 ▶}
25 => App\Items {#2326 ▶}
26 => App\Items {#2325 ▶}
27 => App\Items {#2324 ▶}
28 => App\Items {#2323 ▶}
29 => App\Items {#2322 ▶}
30 => App\Items {#2321 ▶}
31 => App\Items {#2320 ▶}
32 => App\Items {#2319 ▶}
33 => App\Items {#2318 ▶}
34 => App\Items {#2317 ▶}
35 => App\Items {#2316 ▶}
36 => App\Items {#2315 ▶}
37 => App\Items {#2314 ▶}
38 => App\Items {#2313 ▶}
39 => App\Items {#2312 ▶}
40 => App\Items {#2311 ▶}
41 => App\Items {#2310 ▶}
42 => App\Items {#2309 ▶}
43 => App\Items {#2308 ▶}
44 => App\Items {#2307 ▶}
45 => App\Items {#2306 ▶}
46 => App\Items {#2305 ▶}
47 => App\Items {#2304 ▶}
]
}

如何将所有项目的ID传递给我的vue组件,以便可以使用vue动态呈现它们?

谢谢。

2 个答案:

答案 0 :(得分:1)

我认为这是一个数组。因此,您必须使用el: .section-backgroundforeach

答案 1 :(得分:1)

在刀片文件中尝试以下操作:

@foreach ($item as $items)
    <ItemComponent
        v-bind:item="{{ json_encode($item) }}"
    />
@endforeach

这会将完整的项目对象传递给每个ItemComponent,如果您只想传递id,则可以改用:itemId="{{ json_encode($item->id) }}"

如果您希望将循环逻辑保留在Vue中,请参考我以前的http请求而不是内联模板的答案:

相反,您的laravel后端终结点应该在从Vue包装器组件中调用后,以响应主体中的ID数组进行响应。然后,您可以使用v-for指令在Vue中遍历数组中的每个ID。

<template>
    <div>
        <div class="item" v-for="item in items" :key="item.id">
            <ItemComponent :item="item"/>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            items: []
        }
    },
    created: function() {
        // When component instance has loaded (page load)
        // Call your laravel endpoint
        this.$http.get("/laravel/endpoint").then((res) => {
            this.items = res.body.items
        }).catch((error) => {
            console.log(error);
        });
    }
}
</script>

现在,如果要传递一个 ID作为路由参数,则可以在组件中使用$route.params.id来访问它们,其中“ id”是参数的名称您可以通过以下方式在您的Vue路由器中设置

{
    path: '/path/to/view/:id'
    ...
}