0

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?

1
  • create a component that doesn't use the optional-child-component OR let them decide to use the optional-child-component if they want and you don't implement it at all Commented Apr 17, 2020 at 13:19

1 Answer 1

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/[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.

Sign up to request clarification or add additional context in comments.

2 Comments

I will try it out and will let you know if that worked!
Hi! Sorry for the late reply! Things have been busy here. Anyway, your solution has worked !! Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.