Svelte应用表格按钮删除功能异常:数组乱序、名称错乱求助
Svelte应用删除功能异常修复
问题根源
- 点击事件绑定错误:原代码里
on:click={tableClick(table.id)}会在组件渲染时立刻执行tableClick,而非点击按钮时触发,导致删除逻辑提前执行,功能不稳定。 - ID生成逻辑错误:删除表格时修改
tableCounter--,会让新生成的表格ID重复,出现名称混乱的问题。 - 循环缺少唯一键:
{#each}循环未指定唯一标识,Svelte复用DOM元素时会出现顺序错乱。
修复步骤
- 将按钮点击事件改为箭头函数包裹,确保点击时才执行:
on:click={() => tableClick(table.id)} - 删除操作中移除
tableCounter--,让新表格的ID始终递增,保持唯一性 - 给
{#each}循环添加唯一键(table.id),明确每个元素的唯一标识,避免DOM复用错误
修正后的完整代码
<script> let tables = []; let deleteMode = false; let tableCounter = 0; function toggleDeleteMode() { deleteMode = !deleteMode; } function tableClick(id) { if (!deleteMode) { console.log(`Table with id ${id} was clicked`); } else { const tableIndex = tables.findIndex(table => table.id === id); tables.splice(tableIndex, 1); } } function createTable() { tableCounter++; const table = { id: tableCounter, name: "Table" + tableCounter } tables = [...tables, table] } </script> <div id="table-container"> <button on:click={toggleDeleteMode}>Delete Mode</button> {#each tables as table (table.id)} <button on:click={() => tableClick(table.id)} class={!deleteMode ? "table" : "tableDelete"} > {table.name} </button> {/each} <button on:click={createTable} class="add-table" type="button">+</button> </div> <style> #table-container { display: grid; grid-template-columns: repeat(auto-fill, 200px); padding: 24px; gap: 24px; } .tableDelete{ background-color: red; height: 200px; box-sizing: border-box; padding: 16px; border: none; border-radius: 10px; box-shadow: 0 0 7px rgba(0, 0, 0, 0.15); resize: none; font-family: sans-serif; font-size: 16px; } .table { height: 200px; box-sizing: border-box; padding: 16px; border: none; border-radius: 10px; box-shadow: 0 0 7px rgba(0, 0, 0, 0.15); resize: none; font-family: sans-serif; font-size: 16px; } .add-table { height: 200px; border: none; outline: none; background: rgba(0, 0, 0, 0.1); border-radius: 10px; font-size: 120px; color: rgba(0, 0, 0, 0.5); cursor: pointer; transition: background 0.2s; } .add-table:hover { background: rgba(0, 0, 0, 0.2); } </style>
内容的提问来源于stack exchange,提问作者Codseus
相关产品推荐
相关产品推荐

