有没有任何方法可以将component/html传递到Svelte中的字符串中



我试图实现的是将组件传递到变量字符串或类似的解决方案中。我已经尝试过{@htmlsomeVariable},但它只在一个方面对我有效——它意味着从字符串到html的文本。但我需要从HTML到字符串的文本。我尝试过document.elementById((,但总是返回"document is not defined"。下面是我试图实现的一个例子:

App.svelte
<script>
import Component from './component.svelte';
import Description  from './description .svelte';

// How to declare component/html into variable?
let test = 'something like <Component /> but acceptable by variable'
let lala = test;
</script>
<Description {test} />  
Description.svelte
<script>
export let lala;
</script>
{#if something}
{@lala html}
{:else if something }
nope
{/if}

我认为这个问题从HTML字符串中呈现Svelte组件已经有了答案,但我没能让它发挥作用。

我不知道你说的"one_answers"是什么意思;从HTML到字符串的文本";,但是如果你想把一个组件传递给一个子组件,你可以把它作为一个道具传递:
<!-- App.svelte -->
<script>
import Component from './Component.svelte';
import Description  from './Description.svelte';
</script>
<Description component={Component} />  

要显示在变量中定义的组件,可以使用<svelte:component>特殊元素。

<!-- Description.svelte -->
<script>
export let component;
</script>
{#if component}
<svelte:component this={component}></svelte:component>
{:else}
component isn't set
{/if}

这是一个工作的Svelte REPL链接。

如果您想了解有关<svelte:component>特殊元素的更多信息,请查看教程。

最新更新