Mounting a Vue3 component within an established application: Step-by-step guide

Imagine we have already mounted an App in main.js:

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

Now, I want to create a function that is called like this:

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

Typically, we would implement the function above by calling createApp(h(render)) and then mounting its instance wherever needed.

However, the issue arises when the modal instance does not inherit anything from the root App.

For example, if we use provide('root', 'here') in the root App and then call inject('root') in another App, we will not get the expected result of here.

Instead, the result will be undefined since the two Apps do not share the same context.

So, how can we rectify this issue and ensure everything functions correctly?

Answer №1

Here are some suggestions:

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

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

createApp({
  setup() {
    const addNewApp = () => {
      const div = document.createElement('div');
      document.querySelector('#app').appendChild(div);
      createApp({
        setup: () => ({
          ...toRefs(state)
        }),
        template: `<h3>New Dynamic Child App</h3>
                   <input v-model="foo">`
      }).mount(div);
    };
    return {
      ...toRefs(state),
      addNewApp
    }
  }
}).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="addNewApp">Add New Dynamic App</button>
</div>


The key principles to note are:

  • Any app can access or modify a reactive state (...toRefs(state), in both apps)
  • An app can be placed in any <div>, even within another app.

You are able to have multiple apps that share the same reactive state. They can be completely independent in the DOM or nested within each other.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why are my Bootstrap nav-tabs not showing tab-content in MVC?

I'm dynamically creating tab navigation from controllers using a list. <div class=""row> <div class="col-xl-3"> <!-- Tabs nav --> <div class="nav flex-column nav-pills nav-pills-custom" id="v-p ...

Streamlining all icons to a single downward rotation

I am currently managing a large table of "auditpoints", some of which are designated as "automated". When an auditpoint is automated, it is marked with a gear icon in the row. However, each row also receives two other icons: a pencil and a toggle button. W ...

Allow AngularJS to make HTTP POST requests with CORS enabled

I am looking to submit a form to send an HTTP POST request to a server located on a different domain, with CORS enabled in the server script using Node.js. Below is the Angular configuration script: var myApp = angular.module('myApp', ['ng ...

Implementing jQuery functionality on elements that are generated dynamically

I'm facing a challenge when working with dynamic elements in jQuery and I really could use some help. Let me provide an example from my current project: main.js $(function () { renderPlaceList(places); setupVoting(); } The two functions are ...

How can I save files to the ~/Documents directory using Node.js on my Mac computer?

Trying to work with the user's Documents folder in Node.js on macOS: var logger = fs.createWriteStream('~/Documents/somefolderwhichexists/'+title+'.txt'); Encountering an error without clear cause. Error message received: Unca ...

Specialized directive for preventing component creation

I developed a custom directive that checks user roles to determine whether or not a component should be shown. Vue.directive("permission", { bind(el, binding) { Vue.nextTick(() => { el.vFillMarkerNode = document.createComment(''); ...

Receiving no communication from Express Router

Having trouble receiving a response from the server after making get/post requests. I've tried adjusting the order of functions in index.js without success. I also attempted to send a post request using Postman to localhost:8080/register, but the requ ...

What is the best way to ensure that the search box automatically adjusts its position and size regardless of the screen resolution?

I'm currently working on a responsive website project and facing an issue with the absolute positioning of the search bar on the main page, which is crucial for me. Below is the code snippet: <div class="span4"> <form class="well form ...

Using Vue global variables within the <head> section of HTML documents

On my website, I am utilizing Vue version 2.6.11. In the src/main.js file, I have set some global variables based on guidance from this thread as shown below: /* global variables */ Vue.prototype.$frontUrl = "http://localhost:8080/"; Vue.prototyp ...

Updating the NODE_ENV variable in Cypress

Working with Cypress, I have a variable in my code "process.env.VUE_APP_API_URL" that is defined in my .env.development file. I need to change this variable while running Cypress. Any suggestions on how I can achieve this? Just a note: When launching Cyp ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

Upon submitting the form, the dynamic dependent drop-down list fails to offer any available options

Hey there, I've got a form with two drop-down lists: id="dd-1" & id="dd-2". The options in id="dd-2" are generated from the database based on what's selected in id="dd-1"; I'm using onChange=getChildOf(this.value) in id="dd-1" for this ...

react dealing with clicking and blurring at the same time

Is there a way to ensure an input's onBlur event fires only after a button's onClick event is completed? The challenge is that the function relying on the state change caused by the onClick needs to be executed by the onBlur event. Using setTimeo ...

What is the best method to collect information from multiple AJAX requests?

In addition to synchronous AJAX calls, what is the most effective approach for handling a situation like this? var A = getDataFromServerWithAJAXCall(whatever); var B = getDataFromServerWithAJAXCallThatDependsOnPreviousData(A); var C = getMoreDataFromServe ...

What is the reason behind the failure to update the state via a reducer and Object.assign?

I'm attempting to develop a reducer without utilizing ES6. It's an outmoded PHP application that lacks a build process for transpilation. I am initializing the state: let defaultState = { accountTypes: { individual: { c ...

Obtaining the Final Document Identifier for Paginating with valueChanges()

When using valueChanges() in AngularFire to subscribe to Firestore data, I encountered an issue where obtaining the last document reference for pagination was not as straightforward as when using onSnapshot. Unfortunately, the approach I was using with o ...

How can one effectively manage event handling for dynamically generated HTML elements?

Handling events for items already present in the document is straightforward: $(document).ready(function() { $('.element-in-question').on("event", function (event) { //do what you need to do during the event }); }); But what abo ...

How can I modify the color in vue-google-chart when a filter option is selected?

I created a stack column chart with a filter that changes the color to blue when selected. Here is my Vue app: https://codesandbox.io/s/vue-dashboard-chart-6lvx4?file=/src/components/Dashboard.vue I expected the selected color to match the color in the ...

Passing variables dynamically in a created Express.js route

Creating routes in Express.js from a JSON file with the specified structure: { "/home":{ "token":"ksdjfglkas" }, "/logout":{ "token":"ksdjfglksaudhf" } } It is necessary to access the token within the routes function. The JavaScript code ...

position property in div element disrupts slider functionality

I've been working on incorporating a simple slider into my website and stumbled upon this example on jsfiddle My goal is to have the slider positioned "relative" within my site, but when I change the CSS to position: relative;, the slider no longer ...