You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含@foreach的Laravel Blade代码迁移至Vue Inertia?

Laravel Blade @foreach 迁移至 Vue Inertia 数据传递问题解决方案

一、确认数据传递链路(Controller → Inertia → Vue)

首先确保Controller通过Inertia正确返回可序列化的数据:

// 示例Controller代码
public function index()
{
    $items = Item::all(); // 替换为你的实际数据查询逻辑
    return Inertia::render('Items/Index', [
        'items' => $items, // 若需自定义结构,可使用API资源类或toArray()
    ]);
}

注意:Eloquent集合会被Inertia自动序列化,但存在关联模型或敏感字段时,建议用API资源类过滤数据,避免循环引用或冗余字段。

二、Vue组件接收并渲染数据

常见错误写法(未正确接收Inertia props)

<template>
  <div>
    <div v-for="item in items" :key="item.id">{{ item.name }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [] // 手动初始化但未接收Inertia传递的props
    }
  }
}
</script>

正确实现方式

Inertia传递的数据会作为组件props传入,需在Vue中声明并使用:

Script Setup 写法

<template>
  <div class="container">
    <h1>Items List</h1>
    <div v-for="item in items" :key="item.id" class="item-card">
      <p>{{ item.name }}</p>
      <p>{{ item.description }}</p>
    </div>
  </div>
</template>

<script setup>
import { defineProps } from 'vue'

// 声明props并指定校验规则
const props = defineProps({
  items: {
    type: Array,
    required: true,
    default: () => []
  }
})
</script>

Options API 写法

<template>
  <div class="container">
    <h1>Items List</h1>
    <div v-for="item in items" :key="item.id" class="item-card">
      <p>{{ item.name }}</p>
      <p>{{ item.description }}</p>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    items: {
      type: Array,
      required: true,
      default: () => []
    }
  }
}
</script>

三、Blade与Vue逻辑映射对比

原Blade的@foreach逻辑:

<!-- index.blade.php -->
<div class="container">
  <h1>Items List</h1>
  @foreach($items as $item)
    <div class="item-card">
      <p>{{ $item->name }}</p>
      <p>{{ $item->description }}</p>
    </div>
  @endforeach
</div>

Vue中只需将@foreach替换为v-for,注意key值必须唯一(优先使用数据的唯一ID),其余渲染逻辑完全对应。

四、常见问题排查

  • 数据未传递到Vue:在Vue组件中添加console.log(props.items)(或console.log(this.items)),查看控制台确认数据是否存在。若为空,检查Controller是否正确返回数据,或Inertia初始化配置(如app.js中是否正确注册Inertia)。
  • 序列化异常:若数据包含关联模型,需用Item::with('关联模型')->get()预加载;或通过API资源类自定义返回字段,避免循环引用:
    // 示例API资源类
    class ItemResource extends JsonResource
    {
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'description' => $this->description,
            ];
        }
    }
    
    // Controller中使用
    return Inertia::render('Items/Index', [
        'items' => ItemResource::collection(Item::all()),
    ]);
    
  • props名称不匹配:确保Vue组件props的名称与Controller传递的键名完全一致(大小写敏感)。

五、验证渲染结果

启动项目后,通过浏览器开发者工具的Vue DevTools查看组件props是否包含正确的items数组,同时检查页面列表是否正常渲染。

内容的提问来源于stack exchange,提问作者Tim Hacks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 06:26:17