怎样在 Svelte 列表渲染块中指定 key 和 引用 index
key 值也存在于 Svelte 中,它在列表渲染区块中作为最后一个参数存在,使用括号包裹。
<script>
let list = [
{ name: "lilei", age: 21 },
{ name: "hanmeimei", age: 24 },
{ name: "lihua", age: 18 },
{ name: "zhangsan", age: 22 },
];
const remove = (index) => {
list.splice(index, 1);
list = list;
};
</script>
<ul>
<!-- name, age 是对 item 的解构,index 是第二个参数,表示下标,(index) 表示指定的 key,可以是引用类型 -->
{#each list as { name, age }, index (index)}
<li on:click={() => remove(index)}>{name} - {age} - {index}</li>
{/each}
</ul>