2016-05-23 468 views
6

我需要做一些东西在根实例的ready:只有当不存在某些组件(他们没有在HTML中声明)。Vue.js:检查是否组件存在

如何检查是否组件存在?

+2

试'V-REF ',https:// vuejs。org/api /#v-ref,'','if(this。$ refs.compName)'.. – MarcosRJJunior

回答

0

我真的希望有比这更好的答案,但目前这解决了问题。

在准备好了,我访问过this的子元素(可以是也Vue),并检查他们的名字是否是或者不是我所期待的:

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 
      } 
     } 
    } 

您也可以直接,如果你以前访问它们赋予他们在模板的引用: //模板:

<comp v-ref:my_component_ref></comp> 
来自Vue的组件准备

然后:

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

我们可以通过vm.$options获得实例化选项中Vue实例的已加载(全局和/或本地)组件的列表,其中vm是当前的Vue实例。

vm.$options属性包含Vue的实例的整体方案。例如,vm.$options.components返回包含当前Vue instace vm的加载组件的对象。

但是,根据组件注册的方式,全局通过Vue.component()locally within a Vue instance optionsvm.$options.components的结构可能会有所不同。

如果该组件是全局注册的,该组件将被添加到vm.$options.components [[Prototype]]链接或其__proto__

而如果组件的Vue的实例的选项内本地注册,组件将被添加到vm.$options.components对象直接作为自己的财产。所以我们不必走原始链来找到组件。


在下面的例子中,我们将看到如何在两种情况下访问加载的组件。

通知的// [1]// [2]评论中的代码这是有关本地注册的组件。

// the globally registered component 
 
Vue.component('global-child', { 
 
    template: '<h2>A message from the global component</h2>' 
 
}); 
 

 
var localComponent = Vue.extend({ template: '<h2>A message from the local component</h2>' }); 
 

 

 
// the root view model 
 
new Vue({ 
 
    el: 'body', 
 
    data: { 
 
    allComponents: [], 
 
    localComponents: [], 
 
    globalComponentIsLoaded: false 
 
    }, 
 
    // local registered components 
 
    components: { // [1] 
 
    'local-child': localComponent 
 
    }, 
 
    ready: function() {  
 
    this.localComponents = Object.keys(this.$options.components); // [2] 
 
    
 
    this.allComponents = loadedComponents.call(this); 
 
    this.globalComponentIsLoaded = componentExists.call(this, 'global-child'); 
 
    } 
 
}); 
 

 
function loadedComponents() { 
 
    var loaded = []; 
 
    var components = this.$options.components; 
 
    for (var key in components) { 
 
    loaded.push(key); 
 
    } 
 
    return loaded; 
 
} 
 

 
function componentExists(component) { 
 
    var components = loadedComponents.call(this); 
 
    if (components.indexOf(component) !== -1) { 
 
    return true; 
 
    } 
 
    return false; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.24/vue.js"></script> 
 
<h1>A message from the root Vue instance</h1> 
 
<p>All loaded components are: {{ allComponents | json }}</p> 
 
<p>local components are: {{ localComponents | json }}</p> 
 
<p><code>&lt;global-child&gt;</code> component is loaded: <strong>{{ globalComponentIsLoaded }}</strong></p> 
 
<global-child></global-child> 
 
<local-child></local-child>

+0

我真的非常感谢你的解释,不幸的是, 。我想知道在HTML中使用的组件。我做了一个小提琴,我删除了HTML中的元素,但它仍然被识别为加载:https://jsfiddle.net/ncmqhy5n/2/ – vivoconunxino