Element-UI表格删除报错:Cannot read properties of undefined (reading 'id')
解决删除Element-UI表格行时的"Cannot read properties of undefined (reading 'id')"错误
问题根源
报错核心原因是未将表格当前待删除行的数据传递给删除逻辑,组件中props.client始终为undefined,导致访问props.client.id时触发错误。
修复步骤及代码调整
1. 调整组件状态与方法
移除无用的client Prop,改用内部Ref存储当前待删除的客户端数据:
<script setup> const props = defineProps({ clients: Array, }) const confirmingClientDeletion = ref(false) // 新增ref存储当前要删除的client const currentClient = ref(null) const form = useForm() // 修改方法,接收当前行的client数据 const confirmClientDeletion = (client) => { currentClient.value = client confirmingClientDeletion.value = true // 修正无效的setTimeout写法 setTimeout(() => {}, 250) } // 改用currentClient的id拼接路由 const deleteClient = () => { form.delete(route('clients.destroy', currentClient.value.id), { preserveScroll: true, onSuccess: () => closeModal(), onFinish: () => form.reset(), }) } const closeModal = () => { confirmingClientDeletion.value = false currentClient.value = null // 重置当前client form.reset() } </script>
2. 修改表格操作列的点击事件
在Element-UI表格的操作列模板中,通过scope.row获取当前行数据并传递给确认方法:
<template> <div class="px-2"> <div class="md:container-2xl rounded-lg bg-white shadow-lg text-gray-700 text-l font-medium mb-4"> <div class="p-12 content-center"> <el-table :data="clients" style="width: 100%"> <el-table-column prop="id" label="id" width="180" /> <el-table-column prop="companyname" label="Raison Sociale" width="180" /> <el-table-column prop="town" label="Ville" width="120" /> <el-table-column prop="created_at" label="Date de creation" width="150" /> <el-table-column fixed="right" label="Operations" width="200"> <!-- 新增scope参数,传递当前行数据到确认方法 --> <template #default="scope"> <el-button size="small">Modifier</el-button> <el-button size="small" type="danger" @click="confirmClientDeletion(scope.row)">Supprimer</el-button> </template> </el-table-column> </el-table> </div> </div> </div> <DialogModal :show="confirmingClientDeletion" @close="closeModal"> <template #title> Suppression des clients </template> <template #content> Vous êtes sûr de vouloir supprimer définitivement le client? </template> <template #footer> <SecondaryButton @click="closeModal"> Annuler </SecondaryButton> <DangerButton class="ml-3" :class="{ 'opacity-25': form.processing }" :disabled="form.processing" @click="deleteClient" > Supprimer client </DangerButton> </template> </DialogModal> </template>
3. 可选:优化Controller响应(非必须)
如果使用Inertia,推荐用Inertia::location替代普通redirect,确保前端路由正确更新:
use Inertia\Inertia; public function destroy(Client $client) { $client->delete(); return Inertia::location(route('clients.index')); }
核心说明
- Element-UI表格的列模板默认提供
scope对象,scope.row即为当前行的数据源; - 必须将当前行数据传递给删除逻辑,才能获取到正确的
id; - 移除无用的
clientProp,避免混淆数据来源。
内容的提问来源于stack exchange,提问作者Norman
相关产品推荐
相关产品推荐

