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

如何获取与待办清单(Todolist)关联的待办事项(Todo)?已解决

待办清单嵌套展示需求与解决方案

需求说明

  • 预期运行逻辑:登录完成后会加载当前用户的所有待办清单(Todolist),需要获取所有待办清单对应的待办事项(Todo),而非仅加载单个待办清单的待办事项
  • 核心需求:待办事项仅展示在其所属的对应待办清单下

原有实现代码

AXIOS 请求代码

getTodos(todolist) {
    axios
        .get(`http://127.0.0.1:8000/api/todolists/${todolist}/todos`)
        .then((res) => {
            this.todos = res.data;
            console.log(res.data);
        })
        .catch((err) => {
            console.log(err);
        });
},

Vue 模板代码

<div
  v-if="todolists.length > 0 && !loading"
  class="todolist-row h-100 py-5"
  :class="todolists.length == 1 ? 'todolist-1' : ''"
>
  <div class="todolist" v-for="todolist in todolists" :key="todolist.id">
    <div class="td-title">
      <h5 class="text-center m-0 py-2 text-light">
        {{ todolist.title }}
      </h5>
    </div>
    <div class="td-inputs d-flex align-items-center justify-content-center">
      <input class="px-2" type="text" />
      <button type="submit">
        <i class="fas fa-plus fa-2x"></i>
      </button>
    </div>
    <div class="px-2">
      <div v-for="todo in todos" :key="todo.id">
        {{ todo.title }}
      </div>
      <div><i class="fas fa-times" @click="cancel(todolist.id)"></i></div>
    </div>
  </div>
</div>

后端路由定义

Route::get('todolists/{todolist}/todos', 'TodoController@index');

控制器原有代码

public function index(Todolist $todolist) {
    return $todolist->todos;
}

尝试过的无效方案

曾尝试使用计算属性过滤后传入v-for渲染,未生效:

computed: {
    filtered() {
      this.todolists.forEach( todolist => {
        this.todos.filter( todo => todo.todolist_id == todolist.id)
        return this.todos
      })
    }
  },

最终解决方案

仅需在TodolistController中添加->with('todos')方法,即可在返回的待办清单对象数组中嵌套包含对应待办事项的对象数组。之后在Vue模板中直接遍历todolist.todos即可获取对应待办事项,无需额外开发独立接口。

修改后的TodolistController代码

$userTodolist = Todolist::where('user_id', Auth::id())->orderBy('id', 'DESC')->with('todos')->get();

修改后的Vue模板代码

<div v-for="todo in todolist.todos" :key="todo.id">
     {{ todo.title }}
</div>

内容的提问来源于stack exchange,提问作者D.D.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:36:04