Nono.MA

Mount multiple Vue components of the same type

MARCH 8, 2021

If you multiple Vue components of the same type throughout your application but they're not in the same parent DOM element, mounting them may not be as easy as calling their parent.

Mounting multiple Vue components with a shared parent

In this first example, we can mount all of our button-counter components by mounting their parent, #button-container.

<div id="button-container">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>

We just need to make one call.

new Vue({ el: '#button-container' });

But what if our components are spread throughout different HTML elements?

Mount multiple Vue components without a shared parent

Imagine you have components of the same (or different) types spread throughout your website's DOM.

<div>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>

<div>
  <button-counter></button-counter>
</div>

<button-counter></button-counter>

We can iterate through the DOM elements and mount them one by one.

// Obtain all button-counter elements
let elements = document.getElementsByTagName('button-counter');

// Convert HTMLCollection to array
let arr = Array.prototype.slice.call( elements )

// Loop through array and mount all elements
arr.forEach((el) => {
    new Vue( { el });
});

Note that we had to convert the HTMLCollection to a JavaScript array before we could call the .forEach() function to iterate over the button-counter host DOM nodes.

This works with Vue 2, and Vue 3 recently released new features for multi-root components and optional TypeScript support.

CodeJavascriptVue