问题描述
我有一个存储在数据库中的订单列表。我使用每个块来显示所有带有删除按钮的订单。单击删除按钮时,我需要获取已单击列表项的ID,以便可以在数据库中查找该顺序并将其删除。我不知道如何获取已单击列表项的ID并将其传递给handleelete函数。如何在svelte / sapper中做到这一点?
<script>
let orderz =[]
function handlesave() {
//save all the order data to db...
} // handlesave
function handleDelete () {
fetch('order',{
method: 'POST',credentials : 'include',headers: {
'Accept': 'application/json','Content-type' : 'application/json'
},body: JSON.stringify({
// order id to send it to server to delete it from the db
})
}).then(response => response.json())
.then(responseJson => {
console.log("xxxxxxx:",responseJson.orderdetails )
})
.catch(error => console.log(error));
}
</script>
<form on:submit|preventDefault={handlesave}>
<button type="submit">Place Order</button>
</form>
<ul>
{#each orderz as order}
<li >
<p >{order.vendorid} - {order.vendorname} - {order.item}
- {order.price}</p>
<button on:click|once={handleDelete}>Delete</button>
</li>
{/each}
</ul>
解决方法
只需将变量添加到您的删除功能:
function handleDelete (id){
... use id to delete item in database...
}
然后将订单ID也添加到您的on:click:
编辑:on:click函数调用已在其他答案中提及
<button on:click|once={()=>handleDelete(order.id)}>Delete</button>
还有其他方法可以做到这一点,但这是最简单的方法。
如果删除该项,则不需要once
修饰符。
您可能需要一个带有each
循环的键,以便在删除后保持列表的正确更新(在下面的示例中,键= something.id)
{#each things as thing (thing.id)}
<Thing current={thing.color}/>
{/each}
https://svelte.dev/tutorial/keyed-each-blocks
,您可以通过简单地将其作为参数传递给删除函数,以了解单击了哪个id:
function handleDelete(id) {
// Delete logic here
}
<button on:click="{() => handleDelete(id)}">Delete</button>
!请注意,您不应该不直接在标记中调用 handleDelete ,因为这将在呈现时立即执行功能立即(并因此有效地删除您的条目)出现在屏幕上)