【问题标题】:Sorting list of data for Svelte components?Svelte 组件的数据排序列表?
【发布时间】:2022-11-14 06:40:23
【问题描述】:

我在使用 Svelte 组件和数据一致性方面遇到了一点问题。

我有一个使用数组中的名称初始化的公司列表。我正在添加一些特定于组件的变量,因为我想在保存之前保留一些中间状态。

主要 (app.svelte) 组件包含公司数组以及用于对列表进行排序的按钮。

当我尝试对列表进行排序时,列表排序得很好,但组件特定变量没有跟随。

我在https://svelte.dev/repl/ab5dc97a775c4ff48d3527646d913794?version=3.53.1 创建了一个小示例,如您所见,在更改排序顺序时,年龄不按名称排序。

我正在考虑将所有信息存储在 Store 中,但这感觉像是一个笨拙的解决方案,并且违背了将应用程序拆分为组件的目的(如果我愿意,我可以在 app.svelte 中使用一个大数组)。

如何解决我的问题? - 或者我想在这里做一些不可能的事情?

【问题讨论】:

  • 您的问题还应包含 REPL 中显示的代码

标签: svelte svelte-component


【解决方案1】:

您需要在 #each 块中添加一个键,以便排序按预期工作 docs - tutorial

REPL

App.svelte
<script>
    import Greeting from './Greeting.svelte'

    let nameStore = [
        {
            'name': 'Hello', 
        },
        {
            'name':'world',
        },      
    ];

    function sortNameStore(multiplier) {
        nameStore.sort((a,b) => { 
            if (a.name > b.name) {
                return 1 * multiplier;
            }
            if (a.name < b.name) {
                return -1 * multiplier;
            } 
            return 0;
        })
        nameStore = nameStore; // Refresh data
    }
</script>

<div>
    {#each nameStore as item (item)}
    <Greeting item={item}/>
    {/each}

    <button on:click={() => {sortNameStore(1)}}>
        Sort by name LOW to HIGH
    </button>
    <button on:click={() => {sortNameStore(-1)}}>
        Sort by name HIGH to LOW
    </button>

</div>
问候.svelte
<script>
    export let item;
    let age = Math.random() * 60;
</script>

<div>
    Name: {item.name}, age = {age}<br>
</div>

nameStore 在这种情况下,如果仅在 App.svelte 的范围内,则不必是商店。

【讨论】:

    猜你喜欢
    • 2013-10-31
    • 1970-01-01
    • 2014-05-03
    • 2011-07-16
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 2014-06-04
    相关资源
    最近更新 更多