如何在具有相同功能但不同行的表中行中使按钮可单击(不添加/删除/编辑)



例如,打开按钮,如果我按下它应该变成红色,但在其他行的所有按钮也变成红色,因为是在同一个组件上。

脚本

let user = { loggedIn: false };
function toggle(item) {
user.loggedIn = !user.loggedIn;
}
{#if !user.loggedIn}
<button id={item.id} class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-full" on:click={toggle(item)}>
Open
</button>
{/if}  {#if user.loggedIn}
<button   id={item.id} class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-full" on:click={toggle(item)}>
Close
</button>
{/if}

ID在Svelte样式中并没有真正发挥作用(除非您希望它发挥作用)。我认为,目前,您的问题在于您的点击处理程序语法(如H.B.所述),以及您如何将数据传递到您的按钮组件。我也不完全确定item是怎么回事,因为它并没有真正定义在任何地方(也许这是在你的代码的其他地方?)。以你的例子为例,我去掉了一些脂肪,使它更容易在SO上阅读。希望我理解你想做的是正确的。如果没有,请告诉我,我会更新的。REPL链接(更新日期:08.04.2022)

**UPDATE (08.04.2022) **

可以使用事件调度和/或数据绑定。你可能不需要两者,除非你的用例比这篇文章指出的要复杂得多。

事件调度程序:要将事件冒泡回父类,需要导入createEventDispatcher,然后使用它来创建调度程序。当您分派事件时(这里在toggle事件中使用),您可以创建您想要的任何名称并传递您想要的任何数据。然后,在父类中侦听该事件,并为该事件分配一个函数(这里是on:eventNameToListenFor={eventFromApp})。

数据绑定:如果这感觉太沉重,你只需要将更改的数据返回到App,你可以在将其分配给按钮时将其绑定:<Btn bind:user={user} />

Button.svelte(注意on:click处理程序和用户变量的export let)。

<script>
import {createEventDispatcher} from 'svelte';
const dispatch = createEventDispatcher();

export let user = { loggedIn: false};
function toggle() { 
user.loggedIn = !user.loggedIn; 
dispatch("eventNameToListenFor", user);
}
</script>
{#if !user.loggedIn}
<button class="bg-green-500" on:click={()=>toggle()}>
Open
</button>
{:else}
<button class="bg-red-500" on:click={()=>toggle()}>
Close
</button>
{/if}

App.svelte(或任何正在使用按钮)

<script>
import Btn from './Button.svelte'
let users = [{id: 1, loggedIn: false}, {id: 2, loggedIn: false}, {id: 3, loggedIn: true}];
const eventFromApp = (event) => {console.log(event.detail)}
</script>
{#each users as user}
<Btn bind:user={user} on:eventNameToListenFor={eventFromApp}/>
{/each}

最新更新