Snapshot of HTML in Vue3 Proxy object or vitual DOM

415 Views Asked by At

Printing javascript "Proxy" object wrapping my virtual Vue3 app perfectly displays a specific value I would like to extract.

console.log(proxyVueApp) ...outputs beautiful HTML deep down in proxyVueApp.$.vnode.el.outerHTML.

Accessing the prop directly with console.log(proxyVueApp.$.vnode.el) gives me a HTML-comment because it's a virtual DOM: <!---->. console.log(proxyVueApp.$.vnode.el.outerHTML) is undefined.

Is there a way to grap this HTML one way or the other?

Now for the details. Here is how I create my Vue instance, import a dynamic component and mount it all:

const proxyVueApp = createApp({
    render() {
        const relPath = 'some/path';
        const compReference = defineAsyncComponent(() =>
            import(relPath /* @vite-ignore */)
        );
        return h(compReference);
    },
});
const el = document.createElement('div');
const mountedApp = proxyVueApp.mount(el);

Is there no way to extract the HTML im seeing with my own eyes from either my mountedApp or HTMLObjectThingo el? I feel like I'm dealing with a case of Schrödingers cat here. The element is both dead and alive.

2

There are 2 best solutions below

1
Duannx On BEST ANSWER

You can use the way SSR works to achieve your goal

import { createSSRApp } from 'vue'
import { renderToString } from 'vue/server-renderer'

const app = createSSRApp({
  data: () => ({ count: 1 }),
  template: `<button @click="count++">{{ count }}</button>`
})

renderToString(app).then((html) => {
  // this is what you want
  console.log(html)
})
0
Kasper Skov On

Here's my complete solution based on Duannx answer. It's taken out a Storybook lifecycle context:

import { createApp, defineAsyncComponent, h } from 'vue';
import { renderToString } from '@vue/server-renderer';

let html = '';
const tempApp = createApp({
        render() {
            const relPath = 'path/to/component.vue';
            const compReference = defineAsyncComponent(() => import(relPath));
            return h(compReference);
        }
    });
renderToString(tempApp).then((h) => {
        html = h;
});