Vue.js: check if a component exists

前端 未结 6 1256
天命终不由人
天命终不由人 2021-02-12 13:26

I need to do some stuff in the ready: of the root instance only when some components don\'t exist (they weren\'t declared in the HTML).

How can I check if a

6条回答
  •  梦如初夏
    2021-02-12 13:43

    We can get the list of the loaded (global and/or local) components of a Vue instance from the instantiation options which is available through the vm.$options where the vm is the current Vue instance.

    vm.$options property holds the whole options of a Vue instance. For example vm.$options.components returns an object containing the loaded components of the current Vue instace vm.

    However depending on the way how a component is registered, either globally through Vue.component() or locally within a Vue instance options, the structure of the vm.$options.components would be different.

    If the component is registered globally, the component will be added to vm.$options.components [[Prototype]] linkage or its __proto__.

    And if the component is registered locally within the Vue instance options, the component will be added to the vm.$options.components object directly as its own property. So that we do not have to walk the proto chain to find the component.


    In the following example we will see how to access the loaded components in both situations.

    Notice the // [1] and // [2] comments in the code which are related to local registered components.

    // the globally registered component
    Vue.component('global-child', {
      template: '

    A message from the global component

    ' }); var localComponent = Vue.extend({ template: '

    A message from the local component

    ' }); // 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; }
    
    

    A message from the root Vue instance

    All loaded components are: {{ allComponents | json }}

    local components are: {{ localComponents | json }}

    <global-child> component is loaded: {{ globalComponentIsLoaded }}

提交回复
热议问题