在Svelte中,当复选框位于组件中时,如何使bind:group工作?

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

当复选框不在组件中时,我使用bind:group作为复选框。现在,当我尝试使用带有组件标签的复选框时,它不起作用。

CheckboxWithLabel.svelte(组件)

<script>
 export let label="";
 export let bindGroup="";
 export let value="";
</script>
<label class="container">{label}
  <input type="checkbox" bind:group={bindGroup} value={value} />
  <span class="checkmark"></span>
</label>

SettingsSession.svelte(页面)

import CheckboxWithLabel from '@/components/ui/CheckboxWithLabel';


let sessionLengths = [5, 15];
$: console.log('duration', sessionLengths);

...
   <div class="form-group">
       <h5>Select live session durations</h5>
          <CheckboxWithLabel label='5 minutes' bindGroup={sessionLengths} value="5"/>
           <CheckboxWithLabel label='15 minutes' bindGroup={sessionLengths} value="15"/>
           <CheckboxWithLabel label='30 minutes' bindGroup={sessionLengths} value="30"/>
           <CheckboxWithLabel label='45 minutes' bindGroup={sessionLengths} value="45"/>
           <CheckboxWithLabel label='60 minutes' bindGroup={sessionLengths} value="60"/>
           <CheckboxWithLabel label='90 minutes' bindGroup={sessionLengths} value="90"/>
           <CheckboxWithLabel label='120 minutes' bindGroup={sessionLengths} value="120"/>
   </div>
...

一个在没有组件的情况下工作bind:group的简短示例。

<script>
let goodDogs = []
let dogs = ['Roger', 'Syd']
</script>

<h2>
  Who's a good dog?
</h2>

<ul>
  {#each dogs as dog}
    <li>{dog} <input type=checkbox bind:group={goodDogs} value={dog}></li>
  {/each}
</ul>

<h2>
  Good dogs according to me:
</h2>

<ul>
  {#each goodDogs as dog}
    <li>{dog}</li>
  {/each}
</ul>

来源:https://www.freecodecamp.org/news/the-svelte-handbook/#svelte-lifecycle-events

bind svelte svelte-component
1个回答
0
投票

似乎是CheckboxWithLabel.svelte (component)为什么不起作用的问题,是将bindgroup初始化为字符串而不是数组:

<script>
  export let label="Herbert";
  export let bindGroup=[]
  export let value="Herbert";
  export let value2="Robert"
  export let label2="Robert"
</script>

我在这里用您的代码创建了一个REPL,用于检查和测试。

编辑:我刚刚检查了您的REPL。您没有将群组绑定在那里。我更新了it。它看起来应该像这样:

<Checkbox label="Herbert" bind:bindGroup={selectedNames} value="Herbert"/>
<Checkbox label="Robert" bind:bindGroup={selectedNames} value="Robert"/>
<Checkbox label="Mike" bind:bindGroup={selectedNames} value="Mike"/>
© www.soinside.com 2019 - 2024. All rights reserved.