回答
我真的希望有比这更好的答案,但目前这解决了问题。
在准备好了,我访问过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