Vue3: How to mount a component into an existing App?

Viewed 460

Let's say that we have an App was already mounted, in main.js:

createApp(App).mount('#app');

And I'd like to write a function, which should be called like this:

createModal({
  render: () => <SomeComponent />,
});

Normally when we implement functions like above, we just call the createApp(h(render)) function, and then mount its instance in anywhere we want.

But the problem is that when we did, the modal instance won't inherit anything from the root App.

So if we have something like provide('root', 'here') was processed in the root App, and then we call inject('root') in the other App, we won't get the string result here.

Instead, the result will be undefined, Because these two Apps are not sharing the same context.

What should I do to make things right?

1 Answers

Here's what you could do:

const { createApp, reactive, toRefs, defineComponent, computed } = Vue;

const state = reactive({
  foo: 'bar'
})

createApp({
  setup() {
    const addDynamicApp = () => {
      const div = document.createElement('div');
      document.querySelector('#app').appendChild(div);
      createApp({
        setup: () => ({
          ...toRefs(state)
        }),
        template: `<h3>Dynamic child (new App)</h3>
                   <input v-model="foo">`
      }).mount(div);
    };
    return {
      ...toRefs(state),
      addDynamicApp
    }
  }
}).mount('#app')
#app {
  border: 2px solid #f50;
  padding: 1rem;
}
<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
<div id="app">
  <input v-model="foo" />
  <button @click="addDynamicApp">Add dynamic app</div>
</div>


The underlying principles are:

  • any app can read/write from/to a reactive state (...toRefs(state), in both)
  • an app can be mounted in any <div>, even if that div happens to be part of another app.

You can have as many apps, sharing the same reactive state. They can be completely separate in DOM or nested into one another.

Related