在 Svelte 中将项目添加/删除到可写数组存储

问题描述 投票:0回答:0

我有一个 Svelte 存储,它是一个可写数组。

首先,我有一个单独的名称数组,并使用它来填充用户可以单击的选择面板。

想法是,如果他们点击名称,它将出现在下方并添加到数组存储中。

所有这些都按我的意愿工作。 但是,如果用户名已经在商店中,我想删除那个名字.

我看过其他示例,但只能做到这一点,因此不会再次添加名称。如果它已经在商店中,我无法删除该名称。我会很感激任何帮助。

我的代码在下面,但我也创建了一个 REPL:https://svelte.dev/repl/4db04c20d9c94f49832584cf405fdb59?version=3.58.0

app.svelte 文件

            <script>
                import { list } from './plus.js';
                
                let people = [
                    {id: 1, name: "John"},
                    {id: 2, name: "Sue"},
                    {id: 3, name: "Bill"},
                ]
                    
                const addToList = (person) => {
                    console.log('person',person)
                    console.log('len', $list.filter(e => e.name === person.name).length)
                    
                    if ($list.filter(e => e.name === person.name).length > 0) {
                        console.log('remove name if it exists in array already')
                        $list = $list.filter((listItem) => listItem != person.name)
                }else{
                        console.log('add name to array if not there')
                        $list = [...$list, person]          
                    }
                }
                
            </script>

            <div class="person-list">
                {#each people as person}
                <div>
                <h4>{person.name}</h4>
                <button on:click={() => addToList(person)}>●</button>
                </div>
                {/each}
            </div>

            {#each $list as item}
            <p>
                {item.name}
            </p>
            {/each}

plus.js文件

            import { writable } from 'svelte/store';

            export const list = writable([]);
javascript arrays svelte store
© www.soinside.com 2019 - 2024. All rights reserved.