2016-05-23 470 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