[Vuejs]-Make Vue not throw error if component is not defined

1👍

Not sure whether this is the best way but you could maybe check $options.components to see which components are registered.

In the example below there are 3 child components. One of them is registered globally, one is registered locally and the third isn’t registered at all. That third component won’t be rendered.

Vue.component('comp-a', { template: `<div>a</div>` })

new Vue({
  el: '#app',
  
  components: {
    'comp-b': {
      template: `<div>b</div>`
    }
  }
})
<script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>

<div id="app">
  <comp-a v-if="$options.components['comp-a']"></comp-a>
  <comp-b v-if="$options.components['comp-b']"></comp-b>
  <comp-c v-if="$options.components['comp-c']"></comp-c>
</div>

There may be a complication here around case, e.g. kebab-case vs PascalCase, but I doubt that would be an insurmountable obstacle to getting this to work.

Leave a comment