VueJS - lIst of all vue instances on a page

Viewed 1698

Quite simply, given something like the following code, with a mix of new Vue() instances and components, how can I list all Vue instances on a page, and what does that list look like?

<div id="instance1">
{{ name }}
</div>
<div id="instance2">
{{ name }}
</div>
<my-component id="some-element"></my-component>

Javascript:

new Vue({
  el: '#instance1',
  data: {
    name: 'Sammy',
  }
});

new Vue({
  el: '#instance2',
  data: {
    name: 'Bobby',
  }
});

Vue.component('my-component', {
  data: function(){
    return {
      name: 'Mark',
    }
  },
  template: '<div>Hello: {{ name }}</div>',
});
2 Answers

You cannot really do that. You will have to maintain the counter yourself. It means you will have to wrap every invocation to new Vue() like:

let counter = 0;
const rootVueComponents = [];

function makeRootInstance(el, data) {
    const instance = new Vue(el, data);

    rootVueComponents.push(instance);
    counter++;

    return instance;
}

Again, this will only provide you with the list of root Vue instances. If you have a component hierarchy, then it will not work.

And finally, if you really wish to have a list of all the components, then create a global created() mixin for all the Vue components and maintain this counting logic there.

Also, I wonder why you might need this. I don't see the real need to do this unless of course, you are experimenting.

For people who (like me) trying to find a way to check presence of any Vue instances on some page:

It can be done with this code:

Array.from(document.querySelectorAll("*")).filter(el => '__vue__' in el)

Each DOM element that has attached Vue instance must contain __vue__ property.

Related