Student of Science
Student of Science

Reputation: 492

Make Vue not throw error if component is not defined

I'm developing a component which have an optional child component.

<template>
  <div>
     <child-component :propA="valueOfA"/> <!-- this child will certainly appear -->

     <optional-child-component :propB="valueOfB" /> <!-- this child may not appear -->
  </div>
</template>

This is for a library I'm developing. optional-child-component comes from a 3rd-party library that the users of my library may want to use. I won't force them to install 3rd-party libraries if they don't want. The problem is that, currently, if the 3rd-party library is not installed then Vue will throw an error saying that optional-child-component is not defined.

How do I include an optional component in my code given that this component may not be defined/registered?

Upvotes: 0

Views: 139

Answers (1)

skirtle
skirtle

Reputation: 29092

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/[email protected]/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.

Upvotes: 1

Related Questions