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

如何在Svelte中识别InPlaceEdit提交时的目标字段?

解决方法

1. 扩展提交函数以接收字段名

修改submit函数,让它同时接收目标对象和要修改的字段名,这样就能明确知道需要更新哪个字段:

function submit(item, fieldName) {
    return ({ detail: newValue }) => {
        const endpoint = `http://blablabla/${item.id}`;
        const formData = new FormData();

        // 仅提交修改的字段+ID(后端支持部分更新时用这个)
        formData.append('id', item.id);
        formData.append(fieldName, newValue);

        // 若后端要求完整实体,用下面的代码遍历所有字段并覆盖修改值
        // Object.entries(item).forEach(([key, val]) => {
        //     formData.append(key, key === fieldName ? newValue : val);
        // });

        fetch(endpoint, { method: 'PUT', body: formData })
            .then(res => res.json())
            .then(updatedData => {
                console.log('更新成功:', updatedData);
                // 更新本地Store,同步页面数据
                const updatedList = $ExpenseStore.map(i => 
                    i.id === item.id ? { ...i, [fieldName]: newValue } : i
                );
                ExpenseStore.set(updatedList);
            })
            .catch(err => console.error('更新失败:', err));

        console.log(`更新ID ${item.id} 的 ${fieldName} 字段,新值:${newValue}`);
    };
}

2. 在模板中传递字段名

使用InPlaceEdit时,调用submit函数时传入对应的字段名:

{#each $ExpenseStore as expense (expense.id)}
    <InPlaceEdit bind:value={expense.name} on:submit={submit(expense, 'name')}/>
    <InPlaceEdit bind:value={expense.price} on:submit={submit(expense, 'price')}/>
    <!-- 其他字段如expensecategory、monthly_amount等依此类推 -->
{/each}

核心原因与补充说明

之前无法识别修改字段,是因为没有从模板向提交逻辑传递字段名信息。通过显式传入fieldName,就能精准定位要更新的字段。

  • 优先使用"仅提交修改字段"的方式,能减少数据传输量;若后端要求接收完整对象,再用遍历所有字段的方式。
  • 更新本地Store的步骤可以确保页面数据实时同步,无需刷新页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:43:32