【问题标题】:web-component slot content is not displayed不显示 web-component 插槽内容
【发布时间】:2022-01-05 16:47:54
【问题描述】:

我正在使用 svelte 构建自定义元素。下面是精简的组件内容

<template>
    <slot name="description">{ description }</slot>
    <slot name="days">
        { padTime(Math.max(time.days, 0)) }
    </slot>
    <slot name="hours">
        { padTime(Math.max(time.hours, 0)) }
    </slot>
    <slot name="minutes">
        { padTime(Math.max(time.minutes, 0)) }
    </slot>
    <slot name="seconds">
        { padTime(Math.max(time.seconds, 0)) }
    </slot>
</template>

虽然时间相关的广告位得到了很好的更新,但由于某种原因,描述广告位没有更新。

在shadow DOM中更新的很好,但是没有显示出来:

【问题讨论】:

    标签: web-component svelte custom-element


    【解决方案1】:

    您放入插槽中的内容是该插槽的后备内容 - 只有在没有任何内容传递到插槽时才会显示。在您的示例中,您将&lt;div slot="description"&gt;Test&lt;/div&gt; 放在描述槽中,因此不显示后备“预售开始于”。对于其他插槽,您不会将内容传递给它们,因此它们会显示后备内容。

    如果您总是希望显示组件内的内容并且不想从组件外传入任何元素,则可能根本不需要在此处使用插槽。

    <template>
        <div>{ description }</slot>
        <div>
            { padTime(Math.max(time.days, 0)) }
        </div>
        <div>
            { padTime(Math.max(time.hours, 0)) }
        </div>
        <div>
            { padTime(Math.max(time.minutes, 0)) }
        </div>
        <div>
            { padTime(Math.max(time.seconds, 0)) }
        </div>
    </template>
    

    【讨论】:

    • 好吧,这可能是我的错,我有点试图“违反”网络组件的目的。我的目标是制作一个组件来处理逻辑,同时在使用组件的地方完成 CSS 样式和 html 安排。这在某种程度上可行吗?
    • @Syffys 组件的目的是封装一个特性并反复使用它们。也许考虑阅读 Google 和 MDN 的文档 esp re best practice developers.google.com/web/fundamentals/web-components/… 这是在将您的问题理解为评论的黑暗中的一枪。也许在softwareengineering.stackexchange.com 中发布问题或更具体的问题。 HTH
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-16
    • 2019-04-10
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多