使用数组值将第一个(第 n 个?)下拉条目设置为默认值

Setting first (nth?) dropdown entry as default using array values

我有一个下拉列表可以很好地处理简单的值,但我只是尝试使用数组作为值,但现在初始下拉列表条目是空的。

我创建了一个REPL来说明这个问题。如您所见,我也尝试过使用 selected=... 自动 select 第一个条目,但它不起作用。

我唯一能想到的就是再引入一个属性回到简单的值,然后通过过滤原始数组来提取数组,但看起来比较麻烦。我想知道我是否缺少另一种更优雅的方式。

提前致谢!

编辑: 这里是建议的代码示例:

<script>
    const availableFilters = [
        { key: ['filterAll'], display: 'All Columns' },
        { key: ['name1', 'name2' ], display: 'Entry Names' },
        { key: ['ID1', 'ID2' ], display: 'Entry IDs' },
        { key: ['name1'], display: 'Entry 1 Name' },
        { key: ['ID1'], display: 'Entry 1 ID' },
        { key: ['name2'], display: 'Entry 2 Name' },
        { key: ['ID2'], display: 'Entry 2 ID' },
    ];
    
    const simpleAvailableFilters = [
        { key: 'filterAll', display: 'All Columns' },
        { key: 'name1', display: 'Entry 1 Name' },
        { key: 'ID1', display: 'Entry 1 ID' },
        { key: 'name2', display: 'Entry 2 Name' },
        { key: 'ID2', display: 'Entry 2 ID' },
    ];
    
    
    let currentFilter = { key: ['filterAll'], value: "", code: 0 };
    let simpleCurrentFilter = { key: 'filterAll', value: "", code: 0 };
</script>

Dropdown with array values: 
<select bind:value={currentFilter.key}>
    {#each availableFilters as filter, i}
        <option selected={i === 0 ? 'selected' : ''} value={filter.key}>{filter.display} - {i}</option>
    {/each}
</select>
<span>
    Selected key: {currentFilter.key}
</span>
<br/>
Simple Dropdown:
<select bind:value={simpleCurrentFilter.key}>
    {#each simpleAvailableFilters as filter, i}
        <option value={filter.key}>{filter.display} - {i}</option>
    {/each}
</select>
<span>
    Selected key: {simpleCurrentFilter.key}
</span>

试试这个:

let currentFilter = availableFilters[0].key;

并且您可以从 option 中删除 selected={i === 0 ? 'selected' : ''}

https://svelte.dev/tutorial/select-bindings

简单替换

let currentFilter = { key: ['filterAll'], value: "", code: 0 };

来自

let currentFilter = availableFilters[0];

即使该对象具有完全相同的结构,它仍然是与数组中第一个位置的对象不同的对象。 {} === {} // false同样适用于数组。

['filterAll'] === ['filterAll'] // false
'filterAll' === 'filterAll' // true

currentFilter 会有这样的结构

{key: *bindedValue*, display: 'All Columns'}

如果你想提取数组你必须在设置初始值时访问键

let currentFilter = availableFilters[0].key;

并更改选项的绑定

<select bind:value={currentFilter}>

REPL 拥有 Repl 很棒,但最好也包含代码,以防 Repl 可能损坏...