How to migrate child instance creation to Vue 3?

Viewed 166

I’m migrating an app from Vue 2.6 to 3.2, currently in migration build, trying to get rid of all the warnings. I can’t figure out how to rewrite the child instance creation.

Current code that successfully mounts the instance/component programmatically under Vue 2:

import ChildComponent from './ChildComponent'
const Ctor = Vue.extend(ChildComponent)
;(childApp = new Ctor({
  router: this.$router,
  store: this.$store
})).$mount()

I tried the following Vue 3 code, it renders successfully, but shows some warnings:

import ChildComponent from './ChildComponent'
childApp = createApp(ChildComponent)
childApp.use(this.$router)
childApp.use(this.$store)
childApp.mount('#child-container')

The warnings:

[Vue warn]: Component "RouterLink" has already been registered in target app.
[Vue warn]: Component "RouterView" has already been registered in target app.

Here is another Vue 3 version of the code that I tried, this one fails to render and displays an error:

import ChildComponent from './ChildComponent'
childApp = createApp({
    router: this.$router,
    store: this.$store,
    render: () => h(ChildComponent),
})
childApp.mount('#child-container')

The error:

Uncaught TypeError: Cannot read properties of undefined (reading '_modulesNamespaceMap')

I'm using the programmatic approach because it allows to preserve the single instance of the component across different layouts that we're mounting it to.

How do I make it to work under Vue 3 without warnings? Thanks!

1 Answers

I'm not sure but I think re-using this.$router and this.$store may be the problem. Try importing the router and store and use that. Once instance is imported and already used in one Vue instance, it can not be re-used in another Vue instance.

Related