vivoconunxino vivoconunxino - 27 days ago 17
Javascript Question

Vue.js: check if a component exists

I need to do some stuff in the

of the root instance only when some components don't exist (they weren't declared in the HTML).

How can I check if a component exists?

Answer Source

I really hope there is a better answer than this, but for the moment this solves the problem.

In the ready, I access the children elements through this (could be also Vue) and check whether their name is or not what I was expecting:

    ready: function() {

        for (var i = 0; i < this.$children.length; i++) {
            if (
                   this.$children[i].$ == 'my_component_a'
                || this.$children[i].$ == 'my_component_b'
                || this.$children[i].$ == 'my_component_c'
            ) {
                //do stuff

You can also access them directly if you previously assigned them a reference in their template: //template:

<comp v-ref:my_component_ref></comp>

Then from the Vue component ready:

if (this.$refs.my_component_ref){
//do stuff