将 Svelte 生成的节点注入静态 DOM

injecting Svelte-generated nodes into static DOM

我有一个静态 HTML 文件,想用动态 Svelte 组件扩充它:

<ul id="list">
    <li>first</li>
    <!-- dynamic list items should be added in between static ones -->
    <li>last</li>
</ul>

(这是一个简化的示例;"first" 和 "last" 元素更复杂,无法在 Svelte 中重新生成它们。)

import List from "./List.svelte";

new List({
    target: document.querySelector("#list"),
    props: {
        items: ["foo", "bar"]
    }
});
<script>
let items;
</script>

{#each items as item}
<li>{item}</li>
{/each}

虽然这会将动态项目附加到列表的末尾。是否有一种惯用的声明方式将它们插入中间?

我能想到的唯一解决方案是麻烦的、非声明性的 DOM 操作:

<script>
import { onMount } from "svelte";

let items;

onMount(() => {
    let container = ref.parentNode;
    container.removeChild(ref);
    // manually change order
    let last = container.querySelectorAll("li")[1];
    container.appendChild(last);
})
</script>

<span bind:this={ref} hidden />

{#each items as item}
<li>{item}</li>
{/each}

(我什至不确定这是否有效,因为 span 元素不允许作为直接 ul 后代,加上手动丢弃 ref 可能会混淆 Svelte?)

您可以使用 anchor 选项来安装与特定节点相邻的组件:

import List from "./List.svelte";

const target = document.querySelector("#list");
const anchor = target.lastChild; // node to insert component before

new List({
    target,
    anchor,
    props: {
        items: ["foo", "bar"]
    }
});

演示:https://svelte.dev/repl/1a70ce8abf2341ee8ea8178e5b684022?version=3.12.1

完整的 API 记录在此处:https://svelte.dev/docs#Client-side_component_API