如何获取 Svelte 组件中的槽值?

JSN*_*nja 3 svelte

假设我创建了一个名为 Component 的组件,我这样称呼它。

<Component>This text goes in the slot</Component>
Run Code Online (Sandbox Code Playgroud)

在组件内部,我可以用来<slot></slot>在 html 中显示该文本。如何在脚本部分引用它的值?是否存在存储它的变量?

小智 9

要获得插槽内容,您需要应用技巧。

在您的组件中将 包装slots成 aspan并使用绑定元素bind:this

在 Component.svelte 中

<script>
    let data;
    $: console.log(data?.innerHTML)
    $: console.log(data?.innerText)
</script>

<span bind:this={data}><slot></slot></span>

Run Code Online (Sandbox Code Playgroud)

你可以在这个repl中检查它