如何绑定使用 Svelte let 指令声明的变量? [英] How to bind variable declared with Svelte let directive?

查看:24
本文介绍了如何绑定使用 Svelte let 指令声明的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决无法绑定到使用 let: 指令声明的变量"错误.

I'm trying to workaround "Cannot bind to a variable declared with the let: directive" error.

// FancyList.svelte
<script>
    export let items = []   
</script>

<ul>
    {#each items as item, i}
        <li><slot item={item}></slot></li>
    {/each} 
</ul>

// App.svelte
<script>
    import FancyList from './FancyList.svelte'
    let items = [ {x: 'AX', y: 'AY'}, {x: 'BX', y: 'BY'}, {x: 'CX', y: 'CY'}]
</script>

<FancyList bind:items={items} let:item={item}>
    <input type=text bind:value={item.x}>
    <input type=text bind:value={item.y}>
</FancyList>

可用作 Svelte REPL

1) 让 FancyList 传递 item 索引而不是 item 本身并绑定 items[index] 而不是 item.

1) Making FancyList to pass item index instead of item itself and binding items[index] instead of item.

<FancyList items={items} let:index={index}>
    <input type=text bind:value={items[index].x}>
    <input type=text bind:value={items[index].y}>
</FancyList>

可用作 Svelte REPL

这最初会正确呈现,但会在输入值更改时发出ReferenceError: index is not defined"错误.

This will initially render properly but will emit "ReferenceError: index is not defined" error upon input value change.

2) 让 FancyList 传递 onChange 回调而不使用 bind.

2) Making FancyList to pass onChange callback and not using bind.

<FancyList bind:items={items} let:item={item} let:onChange={onChange}>
    <input type=text value={item.x} on:input={e => onChange({...item, x: e.target.value})}>
    <input type=text value={item.y} on:input={e => onChange({...item, y: e.target.value})}>
</FancyList>

可用作 Svelte REPL.

这可行,但要冗长得多.

This works but is significantly more verbose.

推荐答案

这是一个错误,您的第一个解决方案尝试没有奏效 — 我已经提出了一个问题.另一种可能的解决方法是将更新逻辑放在父组件中,这样子组件就不需要对父组件的要求有任何特殊的了解:https://svelte.dev/repl/2d13c33c34f445d99618fbb1bc8bebb9?version=3.6.1.它与您的第二个解决方案大致相同,详细程度相同.

It's a bug that your first solution attempt didn't work — I've raised an issue. Another possible workaround is to put the update logic in the parent component, so that the child component doesn't need to have any special awareness of the parent's requirements: https://svelte.dev/repl/2d13c33c34f445d99618fbb1bc8bebb9?version=3.6.1. It's about the same as your second solution, verbosity-wise.

这篇关于如何绑定使用 Svelte let 指令声明的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆