Search code examples
javascriptvuejs3virtual-dom

Snapshot of HTML in Vue3 Proxy object or vitual DOM


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.


Solution

  • 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)
    })