插槽,具名插槽,作用域插槽
Slots are a handy way to let you define components that can be composed together.
插槽是一种方便的方法,可让您定义可以组合在一起的组件。
And vice versa, depending on your point of view, slots are a handy way to configure a component you are importing.
反之亦然,根据您的观点,插槽是配置导入组件的便捷方法。
Here’s how they work.
这是他们的工作方式。
In a component you can define a slot using the <slot />
(or <slot></slot>
) syntax.
在组件中,可以使用<slot />
(或<slot></slot>
)语法定义<slot></slot>
。
Here’s a Button.svelte
component that simply prints a <button>
HTML tag:
这是一个Button.svelte
组件,它仅打印一个<button>
HTML标记:
<button><slot /></button>
For React developers, this is basically the same as
<button>{props.children}</button>
对于React开发人员,这基本上与
<button>{props.children}</button>
Any component importing it can define content that is going to be put into the slot by adding it into the component’s opening and closing tags:
任何导入它的组件都可以通过将其添加到组件的开始和结束标记中来定义将要放入插槽的内容:
<script>
import Button from './Button.svelte'
</script>
<Button>Insert this into the slot</Button>
You can define a default, which is used if the slot is not filled:
您可以定义一个默认值,如果未填充插槽,则使用该默认值:
<button>
<slot>
Default text for the button
</slot>
</button>
You can have more than one slot in a component, and you can distinguish one from the other using named slots. The single unnamed slot will be the default one:
一个组件中可以有多个插槽,并且可以使用命名插槽将一个插槽与另一个插槽区分开。 单个未命名的插槽将是默认插槽:
<slot name="before" />
<button>
<slot />
</button>
<slot name="after" />
Here’s how you would use it:
使用方法如下:
<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>
And this would render the following to the DOM:
这会将以下内容呈现给DOM:
<p slot="before">Add this before</p>
<button>
Insert this into the slot
</button>
<p slot="after">Add this after</p>
插槽,具名插槽,作用域插槽