【问题标题】:Append svelte component to another component, depending on the viewport width根据视口宽度将苗条组件附加到另一个组件
【发布时间】:2020-11-17 22:56:32
【问题描述】:

有 3 个组件 - A、B、C。 C 组件在 A 中。

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

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

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

【问题讨论】:

    标签: svelte sapper


    【解决方案1】:

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

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

    有一些关于portals,甚至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>
    

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      相关资源
      最近更新 更多