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
相关产品推荐
相关产品推荐

