title: Automatically initialising multiple Vue.js3 Single File Components each within its own Vue instance
body: <p>I'd like to have multiple Vue3 components. Each as a separate Vue instance, and all automatically loaded.</p>
  <p>Why? Because I want to use them on a page where there's potentially many other JS scripts that alter the page so I cannot change the DOM for them (by globally initialising Vue) and I want not to worry that they will mess with my Vue components - so mounting all my components to some one big Vue instance like <code>&lt;body id=&quot;app&quot;&gt;</code> is not an option.</p>
  <p>With Vue2 it was a bit easier but does not work with Vue3. Now after some fight I worked out a solution for Vue3 it works fine but it seems ugly in my eyes so I assume there's a better one :)</p>
  <p>I'm using (<a href="https://laravel-mix.com/docs/6.0/vue" rel="nofollow noreferrer">laravel-mix</a> - <a href="https://webpack.js.org/" rel="nofollow noreferrer">Webpack</a> solution for building my files).</p>
  <p>Here's my HTML file with the components embedded:</p>
  <pre><code>// index.php
  
  &lt;TestOne data-vue-component=&quot;TestOne&quot; /&gt;
  &lt;TestTwo data-vue-component=&quot;TestTwo&quot; /&gt;
  &lt;TestOne data-vue-component=&quot;TestOne&quot; /&gt;
  </code></pre>
  <p>And here's my JS file for loading those components:</p>
  <pre><code>// index.js
  
  import { createApp } from 'vue';
  
  const vueComponents = document.querySelectorAll('[data-vue-component]');
  if (vueComponents.length) {
      vueComponents.forEach((elem) =&gt; {
  
         const componentName = elem.getAttribute('data-vue-component');
         const app = createApp(require(`./components/${componentName}/${componentName}.vue`).default);
         app.mount(elem);
      }
  }
  </code></pre>
  <p>So I look for the Vue components using data attribute <code>data-vue-component</code> and then for each one found I get the component's name, create a Vue3 instance importing the component at the same moment. Finally I mount it and do the same with the next one.</p>