如何在 Svelte 3 中拥有条件属性?

How to have a conditional attribute in Svelte 3?

下面的checkbox组件有没有更简单的写法:

<script>
  export let disabled = false;
</script>

{#if disabled}
  <label class="checkbox" disabled>
    <input type="checkbox" {disabled} />
    <slot></slot>
  </label>
{:else}
  <label class="checkbox">
    <input type="checkbox" {disabled} />
    <slot></slot>
  </label>
{/if}

<label disabled="false"> 是不可接受的,因为 Bulma 有 CSS class .checkbox[disabled].

disabled || null(或disabled || undefined)就可以了:

<label class="checkbox" disabled={disabled || null}>
  <input type="checkbox" {disabled} />
  <slot></slot>
</label>

来自docs

... [A]ttributes are included unless their value is nullish (null or undefined).

<input required={false} placeholder="This input field is not required">
<div title={null}>This div has no title attribute</div>