Vue.js: check if a component exists

前端 未结 6 1428
天命终不由人
天命终不由人 2021-02-12 13:26

I need to do some stuff in the ready: of the root instance only when some components don\'t exist (they weren\'t declared in the HTML).

How can I check if a

6条回答
  •  不要未来只要你来
    2021-02-12 14:00

    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].$options.name == 'my_component_a'
                    || this.$children[i].$options.name == 'my_component_b'
                    || this.$children[i].$options.name == 'my_component_c'
                ) {
                    //do stuff
                }
            }
        }
    

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

    
    

    Then from the Vue component ready:

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

提交回复
热议问题