回答
我真的希望有比這更好的答案,但目前這解決了問題。
在準備好了,我訪問過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
}
我們可以通過vm.$options
獲得實例化選項中Vue實例的已加載(全局和/或本地)組件的列表,其中vm
是當前的Vue實例。
vm.$options
屬性包含Vue的實例的整體方案。例如,vm.$options.components
返回包含當前Vue instace vm
的加載組件的對象。
但是,根據組件註冊的方式,全局通過Vue.component()
或locally within a Vue instance options,vm.$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><global-child></code> component is loaded: <strong>{{ globalComponentIsLoaded }}</strong></p>
<global-child></global-child>
<local-child></local-child>
我真的非常感謝你的解釋,不幸的是, 。我想知道在HTML中使用的組件。我做了一個小提琴,我刪除了HTML中的
我不知道,如果你需要一個動態的方法,但是這可能有助於確定是否組件存在:
Vue.options.components['CompOne']
發現:
試'V-REF ',https:// vuejs。org/api /#v-ref,' ','if(this。$ refs.compName)'.. –
MarcosRJJunior