首页 > 解决方案 > 绑定到对象集合

问题描述

我有一个对象映射,需要将它们的一些字段绑定到标签。当然,我可以将映射转换为数组并使用#each,但在这种情况下,对单个映射条目的更新将更新对所有标签的绑定。我想要原子更新,即将输入绑定到单独的对象,同时使用#each 来构建整个东西(手动映射 50 个左右的项目并不有趣)。有什么办法可以做到这一点?

标签: svelte

解决方案


解决方案(有点骇人听闻)如下:

App.svelte:

    <script>
    import Update from "./Update.js"
    
        let items = [
        { id: 1, value: 'a' },
        { id: 2, value: 'b' },
        { id: 3, value: 'c' },
        { id: 4, value: 'd' },
        { id: 5, value: 'e' }
    ];
   </script>

   <style>
    :global(.myclass) {
        animation: pulse 2s ease-out
    }
    
    @keyframes pulse {
     0%, 75% {
       background-color: red;
     }
     100% {
       background-color: white;
    }
   }
</style>

{#each items as item (item.id)}
    <input type="text" bind:value={item.value} use:Update={item.value}>
{/each}

Update.js 动作:

 export default function update(node, foo) {
 let faa = foo
 return {
     update(foo) {
       if (foo === faa) return
       faa = foo
       // rest of code will only be executed if the value really changed
       node.style.animation = 'none';
       node.offsetHeight; /* trigger reflow */
       node.style.animation = null; 
       node.classList.add("myclass");
     }
   }
 }

推荐阅读