根据视口宽度将 svelte 组件附加到另一个组件

Append svelte component to another component, depending on the viewport width

有 3 个组件 - A、B、C。 C分量在A.

如果视口宽度小于 x px 需要将 C 组件移到 B 中。

使用 vanilla js 很容易做到。是否可以在不创建两个 C 组件的情况下在 svelte 中进行操作?

vanilla-js-示例 - <https://codepen.io/vladbelozertsev/pen/eYzoYmO?editors=1111>

不,确实没有官方支持的方式/构造来做到这一点。在 Svelte 中,组件在树中移动的唯一情况是使用键控列表:

{#each items as item}
  <MyComponent key={item.id}>{item.text}</MyComponent>
{/each}

有一些关于 portals, and even a lib 的讨论。

否则你仍然可以自己实现类似的东西,方法是使用 DOM API 自己移动 Svelte 组件中的元素。

Bellow 是一个移动“组件”的示例(实际上,组件的元素——组件本身在虚拟 Svelte 组件树中保持在同一位置)——REPL.

Child.svelte

<div>I am Child</div>

App.svelte

<script>
    import Child from './Child.svelte'
    
    let wrapper
    let left
    let right
    
    const goLeft = () => {
        left.appendChild(wrapper)
    }
    
    const goRight = () => {
        right.appendChild(wrapper)
    }
</script>

<button on:click={goLeft}>Left</button>

<button on:click={goRight}>Right</button>

<div>
    <div class="container left" bind:this={left} />
    <div class="container right" bind:this={right} />
</div>

<div bind:this={wrapper}>
    <Child />
</div>