Nono.MA

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.

MARCH 8, 2021

Change this.

window.Vue = require('vue');

For this.

window.Vue = require('vue').default;

Then this should work.

window.Vue = require('vue').default;
window.VueResource = require('vue-resource');
window.Vue.use(window.VueResource);

Want to see older publications? Visit the archive.

Listen to Getting Simple .