Skip to content

[Feature Request] Rendering outside of the Vue-App #410

@douglasg14b

Description

@douglasg14b

I see the TODO in the docs about this.

Is this possible now? if so, how? if I try this right now (rendering a PortalTarget somewhere else) the portal that points at it never seems to render it's content.

My use case:

A userscript that adds components/UI to an existing page. Often I will need to react to certain DOM elements appearing and add additional components to them, which means rendering Vue components outside of the scope of the original app.

This is possible today the ahrd way, but I run ito a ton of caveats such as losing access to plugin data and what not on the original app instance.

export function injectVueComponent<TComponent extends Parameters<typeof h>[0]>(
    domSelector: string,
    component: TComponent,
    app: App,
    propsGetter: () => Record<string, unknown>
) {
    let vueComponent: VNode | null = null;
    let mountTarget: Element | null = null;

    watchForElement(domSelector, {
        onAppear: (element) => {
            mountTarget = element;
            const props = propsGetter();

            vueComponent = h(component, props);
            vueComponent.appContext = app._context; // Set the app context to the component

            render(vueComponent, element);
        },
        onVanish: () => {
            if (mountTarget) {
                render(null, mountTarget);
            }
            vueComponent = null;
            mountTarget = null;
        },
    });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions