英文:
Two-way binding with <select> loop in Svelte
问题
考虑以下的 Svelte 代码(在此处尝试)。
当我更改下拉菜单的值,然后单击按钮调用 addFruit
时,fruits
的各个元素保持不变。
我如何为这些动态添加的元素实现绑定?
<script>
let options = [
{"id": "fruit1", "name": "Apple"},
{"id": "fruit2", "name": "Banana"},
];
let fruits = [
{"fruit_id": "fruit1"}
];
function addFruit() {
fruits.push({ fruit_id: "fruit1" });
fruits = fruits;
console.log(fruits);
}
</script>
{#each fruits as fruit, i}
<select bind:value={fruit.fruit_id}>
{#each options as option}
<option value={option.id}>{option.name}</option>
{/each}
</select>
{/each}
<button on:click={addFruit}>+</button>
英文:
Consider the following Svelte code (try it here).
When I change the value of a dropdown, and then click the button to call addFruit
, then the individual elements of fruits
remain unchanged.
How can I implement binding for these dynamically-added elements?
<script>
let options = [
{"id": "fruit1", "name": "Apple"},
{"id": "fruit2", "name": "Banana"},
];
let fruits = [
{"fruit_id": "fruit1"}
];
function addFruit() {
fruits.push({ fruit_id: "fruit1"});
fruits = fruits;
console.log(fruits);
}
</script>
{#each fruits as fruit, i}
<select value={fruit.fruit_id}>
{#each options as option}
<option value={option.id}>{option.name}</option>
{/each}
</select>
{/each}
<button on:click={addFruit}>+</button>
答案1
得分: 1
现在一切都是单向的(进入元素)。你必须像这样添加绑定:
<select bind:value={fruit.fruit_id}>
英文:
Right now everything is one-way (into the elements). You have to add bindings like this:
<select bind:value={fruit.fruit_id}>
答案2
得分: -1
我尝试解决这个问题
你需要这个: 解决方案
代码:
<script>
let options = [
{"id": "fruit1", "name": "Apple"},
{"id": "fruit2", "name": "Banana"},
{"id": "fruit3", "name": "Mango"},
{"id": "fruit4", "name": "Coco"},
];
let fruits = [
{"fruit_id": "fruit1"}
];
function addFruit() {
// fruits.push({ fruit_id: kit});
fruits = [...fruits,{ fruit_id: kit}];
console.log(fruits);
}
let kit=options[0].id;
$: console.log(kit);
</script>
<select bind:value={kit}>
{#each options as option}
<option value={option.id}>{option.name}</option>
{/each}
</select>
<button on:click={addFruit}>+</button>
英文:
I tried for Solving this Issue
Do u need this : solution
code :
<script>
let options = [
{"id": "fruit1", "name": "Apple"},
{"id": "fruit2", "name": "Banana"},
{"id": "fruit3", "name": "Mango"},
{"id": "fruit4", "name": "Coco"},
];
let fruits = [
{"fruit_id": "fruit1"}
];
function addFruit() {
// fruits.push({ fruit_id: kit});
fruits = [...fruits,{ fruit_id: kit}];
console.log(fruits);
}
let kit=options[0].id;
$: console.log(kit);
</script>
<select bind:value={kit}>
{#each options as option}
<option value={option.id}>{option.name}</option>
{/each}
</select>
<button on:click={addFruit}>+</button>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论