如何替换 Svelte 中目标的内容而不是附加到子项?

How to replace the contents of a target in Svelte instead of appending to children?

调用 new Component({ target }) 将组件附加到目标,我想用新组件替换目标的所有旧内容。我该怎么做?

如果您要混合服务器呈现的标记,最好使用 hydrate: true 选项 (docs here)。

如果target之前被一个Svelte组件占用,最好调用那个组件的$destroy()方法。

否则,最简单的方法就是清空 target 元素:

target.innerHTML = '';
new Component({ target });

我遇到了同样的问题,我正在单独创建 HTML 回退,只是想用 client-side 完全反映静态 html 的 Svelte 组件来补充整个 dom ].但是,使用 the docs 中的方法会创建两个嵌套的 <html> 元素,因为它是附加到目标而不是替换它。

抓住我要替换的元素的“父级”似乎对我有用:

import App from './App.svelte';

let target = document.querySelector('html').parentNode;

new App({
  target: target,
  hydrate: true
});

在我的具体情况下,可以更简单地写成:

import App from './App.svelte';

new App({
  target: document,
  hydrate: true
});

替换顶级 <html> 元素会产生一些控制台错误,但这里有一些屏幕截图和更多详细信息,说明我们如何在我们的项目中实施它,以防有帮助:https://github.com/plentico/plenti/issues/65#issuecomment-696391302

function replaceTarget (target) {
    const component = new MySvelteComponent({
        target: target.parentElement,
        anchor: target,
    });
    target.remove();
}

这会将新组件添加到目标元素之前(在目标的父元素中),然后删除目标。

关于anchor的相关文档:https://svelte.dev/docs#Creating_a_component

target === <body> 一起使用可能不是一个好主意。