Laravel结合Inertia.js开发如何实现编辑页关联数据对应checkbox预选中
问题根源
- 重复列表是因为你用了两层嵌套
v-for:外层遍历全量concern,内层遍历客户关联的concern,每个全量concern都会按照客户关联的concern数量重复渲染N次,你看到4份就是客户当前关联了4个concern。 - 选中逻辑冗余:用
v-model绑定数组类型的form.concerns时,只要input的value值存在于数组中就会自动选中,不需要手动加checked属性,也不需要嵌套循环匹配id。
解决方案
1. 优化ClientController.php
原写法冗余,路由模型绑定已经拿到了$client实例,不需要重复查询,直接预加载关联关系即可:
/** * Show the form for editing the specified resource. * * @param \App\Models\Client $client * @return \Illuminate\Http\Response */ public function edit(Client $client) { $concerns = Concern::all(); // 直接给现有client实例加载关联关系 $client->load('concerns'); return Inertia::render('Client/Edit', [ 'client' => $client, 'concerns' => $concerns, ] ); }
2. 修改Edit.vue模板
删掉内层嵌套的v-for和多余的判断逻辑,仅遍历全量concern即可:
<ul id="concerns"> <li v-for="concern in concerns" :key="concern.id"> <input type="checkbox" :id="`concern-${concern.id}`" :name="concern.concern_slug" :value="concern.id" v-model="form.concerns" /> <label :for="`concern-${concern.id}`">{{ concern.concern }}</label> </li> </ul>
3. 修改Edit.vue数据初始化逻辑
初始化form.concerns时直接提取客户已关联concern的id数组,即可实现默认选中:
export default { props: { errors: Object, concerns: Array, // 建议把类型从Object改为Array,避免类型警告 client: Object, clientConcerns: Array, // 建议把类型从Object改为Array,避免类型警告 }, data () { return { form: { first_name: this.client.first_name, last_name: this.client.last_name, email: this.client.email, address: this.client.address, city: this.client.city, postal_code: this.client.postal_code, province: this.client.province, preferred_day: this.client.preferred_day, preferred_time: this.client.preferred_time, preferred_frequency: this.client.preferred_frequency, goals: this.client.goals, // 提取客户已有concern的id作为初始值 concerns: this.client.concerns.map(item => item.id), }, } }, // 其余逻辑保持不变 }
内容的提问来源于stack exchange,提问作者NSaid
相关产品推荐
相关产品推荐

