To do I call Vue app.mount('#myAppID') a second time if the div with that ID is removed from the DOM and added back later?

31 Views Asked by At

I have one Vue component (a compiled single .js file) that is a header, and another Vue app that contains a lot of pages. If I load in the second (compiled) vue app.js file, AND the DOM element with the expected ID is present, then it loads fine at first. But, if I change pages with a router, and that DOM becomes unloaded, then when I switch back to that initial page, the Vue Header app doesn't load, the stays empty.

Same thing happens if I try to load that script first, and the DOM element with the expected ID isn't present, it won't load then, and it won't load later.

So, here is what the code block looks like with the Vue header. This works, once but not a second time. I think in part because the script is already added to the document so calling it again would add a duplicate. So ideally, I would just load it once, but be able to re-initialize or re-mount it again when needed.

<template>
  <div id="vue-header"></div>
</template>

<script>
  export default {
    mounted() {
      console.log("Vue header mounted event")
      let testScript = document.createElement('script')
      testScript.setAttribute('src', 'https://site****URL.com/Vue/vue-header.js')
      document.head.appendChild(testScript)
    }
  }
</script>

Within the vue-header.js in main.ts I have the standard stuff, but the important part to know is that it targets that id #vue-header

import App from './App.vue'

const app = createApp(App);

app.mount('#vue-header');

So, is there any simple way to re-initialize that app once it gets unloaded? I am not sure how (or if it is possible) to reference and target the imported block of script to call the app.mount for it a second time. If this is possible, I would change the import to happen once in the root Vue app, and just call the initialize/mount of header as needed on router change.

I do realize there might be libraries to handle this scenario, but I was wondering if there was a plain JS solution, to keep the apps as small as possible.

0

There are 0 best solutions below