Vue.js:检查组件是否存在

新手上路,请多包涵

仅当某些组件不存在(它们未在 HTML 中声明)时,我才需要在根实例的 ready: 中做一些事情。

如何检查组件是否存在?

原文由 javier_domenech 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

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

在准备就绪时,我通过 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
            }
        }
    }

如果您之前在其模板中为它们分配了引用,您也可以直接访问它们: //template:

 <comp v-ref:my_component_ref></comp>

然后从 Vue 组件准备好:

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

原文由 javier_domenech 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

vm.$options 属性包含 Vue 实例的全部选项。例如 vm.$options.components 返回一个包含当前 Vue 实例 vm 的加载组件的对象。

但是,根据组件的注册方式,无论是通过 Vue.component() 全局注册还是 在 Vue 实例选项中本地 注册, vm.$options.components 的结构都会有所不同。

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

如果组件在 Vue 实例选项中本地注册,该组件将作为自己的属性直接添加到 vm.$options.components 对象中。这样我们就不必遍历 proto 链来查找组件。


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

注意代码中与本地注册组件相关的 // [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>

原文由 Hashem Qolami 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题