【问题标题】:Slots not working in my VUE CustomElement (defineCustomElement)插槽在我的 VUE CustomElement 中不起作用(defineCustomElement)
【发布时间】:2022-11-11 05:42:10
【问题描述】:

我从网络上的各种来源(文档、stackoverflow 等)创建了 VUE 3 中的 CustomElement 初始化。

不幸的是,没有人讨论如何在这种类型的初始化中处理槽。

如果我理解正确,它应该根据文档工作。
https://vuejs.org/guide/extras/web-components.html#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,
        setup(props, { emit }) {
            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,
                });
        },
    });

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

我怀疑我在初始化期间忘记了一些东西,并且插槽的内容没有传递。

【问题讨论】:

    标签: vue.js vuejs3


    【解决方案1】:

    有点晚了,但我们正在使用这种方法使用 Vue 3 和这个解决方法来做 Web 组件,将 Vue 组件上下文添加到自定义元素。

    setup(props, { slots })
    

    接着:

    return () =>
       h(component, {
         ...props,
         ...slots
       });
    

    感谢 @tony19,此解决方法的作者。

    【讨论】:

      猜你喜欢
      • 2018-08-15
      • 2017-09-08
      • 2021-12-22
      • 2021-02-06
      • 1970-01-01
      • 2019-06-08
      • 2021-11-26
      • 2014-12-12
      • 2021-10-18
      相关资源
      最近更新 更多