Vue.js:检查组件是否存在 [英] Vue.js: check if a component exists

查看:73
本文介绍了Vue.js:检查组件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当某些组件不存在(它们未在HTML中声明)时,我才需要在根实例的 ready:中进行一些操作.

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 component exists?

推荐答案

我真的希望有比这更好的答案,但是目前这可以解决问题.

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

准备好了,我通过 this (也可以是 Vue )访问子元素,并检查它们的名称是否与我期望的一样:

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:

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

然后从Vue组件准备好:

Then from the Vue component ready:

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

这篇关于Vue.js:检查组件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆