如何在Svelte中使用槽来定义可以组合在一起的组件

133 阅读1分钟

如何在Svelte中使用槽来定义可以组合在一起的组件

槽是一种方便的方式,可以让你定义可以一起组成的组件。

反之亦然,根据你的观点,槽是一种方便的方式来配置你正在导入的组件。

以下是它们的工作原理。

在一个组件中,你可以使用<slot /> (或<slot></slot> )的语法定义一个槽。

这里有一个Button.svelte 组件,它简单地打印了一个<button> HTML标签。

<button><slot /></button>

对于React开发者来说,这基本上等同于<button>{props.children}</button>

任何导入它的组件都可以通过在组件的开头和结尾标签中加入内容来定义要放入槽中的内容。

<script>
import Button from './Button.svelte'
</script>

<Button>Insert this into the slot</Button>

你可以定义一个默认值,如果槽没有被填满,就会使用它。

<button>
  <slot>
    Default text for the button
  </slot>
</button>

你可以在一个组件中拥有一个以上的槽,你可以用命名的槽来区分一个和另一个。单个未命名的槽将是默认槽。

<slot name="before" />
<button>
  <slot />
</button>
<slot name="after" />

下面是你将如何使用它。

<script>
import Button from './Button.svelte'
</script>

<Button>
  Insert this into the slot
  <p slot="before">Add this before</p>
  <p slot="after">Add this after</p>
</Button>

而这将向DOM呈现以下内容。

<p slot="before">Add this before</p>
<button>
  Insert this into the slot
</button>
<p slot="after">Add this after</p>