You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 defineCustomElement自定义元素Slots失效问题求助

Vue3 自定义元素集成Pinia后插槽失效问题排查

问题根源

你封装的defineCustomElementWrapped函数在setup阶段没有传递插槽上下文给目标组件。官方defineCustomElement会自动处理Web Components插槽与Vue组件插槽的映射,但你自定义的setup逻辑里,返回的h调用遗漏了插槽参数,导致组件无法获取外部传入的插槽内容。

修复方案

修改setup函数,解构获取slots参数,并在h函数的第三个参数位置传入slots:

import { defineCustomElement, h, createApp, getCurrentInstance } from "vue";

import audioplayer from "./my-audioplayer.ce.vue";
import audioplayerlight from "./my-audioplayerlight.ce.vue";
import { createPinia } from "pinia";

const pinia = createPinia();
export const defineCustomElementWrapped = (component, { plugins = [] } = {}) =>
    defineCustomElement({
        styles: component.styles,
        props: component.props,
        // 解构出slots参数
        setup(props, { emit, slots }) {
            const app = createApp();
            plugins.forEach((plugin) => {
                app.use(plugin);
            });
            const inst = getCurrentInstance();
            Object.assign(inst.appContext, app._context);
            Object.assign(inst.provides, app._context.provides);
            return () =>
                h(component, {
                    ...props,
                }, slots); // 将slots传入h函数
        },
    });

customElements.define(
    "my-audioplayer",
    defineCustomElementWrapped(audioplayer, { plugins: [pinia] })
);
customElements.define(
    "my-audioplayerlight",
    defineCustomElementWrapped(audioplayerlight, { plugins: [pinia] })
);

补充说明

  • 具名插槽无需额外处理,直接传入slots后,Vue会自动匹配组件内的同名插槽(如<slot name="footer"></slot>)。
  • 确保你的.ce.vue组件使用标准Vue插槽语法,Web Components的插槽内容会自动映射到对应Vue插槽。

内容的提问来源于stack exchange,提问作者bschauer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:35:20