Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!