Laravel+惯性+Vuejs:分页
当我获得所有记录时,它会起作用:
...
$items = Item::all();
return Inertia::render('Rentals/Items', ['items' => $items]
);
但是当我尝试分页时,它崩溃了:
...
$items = Item::paginate(15);
return Inertia::render('Rentals/Items', ['items' => $items]
);
我收到此错误:
Uncaught (in promise) TypeError: Cannot read property 'id' of null
请帮忙。我究竟做错了什么?我已经被困了好几天了。
回答
Creator of Inertia.js here.
So, you can totally use the Laravel paginator with Inertia, you just need to setup your page components to be compatible.
首先,确保您只将项目数据返回给您实际需要的客户端。您可以使用新的分页通过方法这一点。
$items = Item::paginate(15)->through(function ($item) {
return [
'id' => $item->id,
'name' => $item->name,
// etc
];
});
return Inertia::render('Rentals/Items', ['items' => $items]);
$items = Item::paginate(15)->through(function ($item) {
return [
'id' => $item->id,
'name' => $item->name,
// etc
];
});
return Inertia::render('Rentals/Items', ['items' => $items]);
接下来,客户端,您需要一个分页组件来实际显示分页链接。这是Ping CRM 演示应用程序中的一个示例组件,使用 Tailwind CSS 构建。
最后,要在页面组件中显示项目和分页链接,请使用items.data和items.links道具。像这样的东西:
<template>
<div v-if="links.length > 3">
<div class="flex flex-wrap -mb-1">
<template v-for="(link, key) in links">
<div v-if="link.url === null" :key="key" class="mr-1 mb-1 px-4 py-3 text-sm leading-4 text-gray-400 border rounded" v-html="link.label" />
<inertia-link v-else :key="key" class="mr-1 mb-1 px-4 py-3 text-sm leading-4 border rounded hover:bg-white focus:border-indigo-500 focus:text-indigo-500" :class="{ 'bg-white': link.active }" :href="link.url" v-html="link.label" />
</template>
</div>
</div>
</template>
<script>
export default {
props: {
links: Array,
},
}
</script>
您可以在Ping CRM 演示应用程序中找到一个完整的工作示例。