只有当某些组件不存在(它们未在 HTML 中声明)时,我才需要在根实例的 ready:
中做一些事情。
如何检查组件是否存在?
最佳答案
我们可以从 vm.$options
可用的实例化选项中获取 Vue 实例的已加载(全局和/或本地)组件列表。其中 vm
是当前的 Vue 实例。
vm.$options
属性包含 Vue 实例的全部选项。例如 vm.$options.components
返回一个包含当前 Vue 实例 vm
加载组件的对象。
然而,取决于组件的注册方式,可以通过 Vue.component()
全局注册。或 locally within a Vue instance options ,vm.$options.components
的结构会有所不同。
如果组件是全局注册的,组件将被添加到vm.$options.components
[[Prototype]]链接或其__proto__
。
如果组件在 Vue 实例选项中本地注册,组件将作为自己的属性直接添加到 vm.$options.components
对象中。这样我们就不必遍历原型(prototype)链来查找组件。
在下面的示例中,我们将看到如何在两种情况下访问加载的组件。
注意代码中的//[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>
关于javascript - Vue.js:检查组件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37389788/