nuxt / components

Scan and auto import components for Nuxt.js 2.13+
MIT License
887 stars 48 forks source link

feat: get list of components at runtime #227

Closed Rigo-m closed 3 years ago

Rigo-m commented 3 years ago

Is your feature request related to a problem? Please describe. I want to leverage <component :is="..." /> to load a component dynamically, but I'd also like to know if that component is resolvable (i.e.: it exists) or not. Describe the solution you'd like I'd like to have a variable injected in the context that tells me the list of components, so that I can throw an error if the component does not exist.

kissu commented 3 years ago

Did you tried this one? https://github.com/blokwise/dynamic#readme

pi0 commented 3 years ago

@kissu Functionality of mentioned module is duplicate in the last version of nuxt/components, you can directly use <component :is="">. And other than integration with vue-lazy-hydration (#104) I do not recommend using it.

I think what this issue requires, is a way to check the existence of a component before using it. While we can make it sexier with a wrapper component like <NuxtComponent :name=""> or $components.has(), we can do this like this with Vue options api:

<component :is="componentId" v-if="$options.components[componentId]" />

Or from js:

import Vue from 'vue'

const componentExists = id => !!Vue.options.components[id]

Sandbox: https://codesandbox.io/s/immutable-wave-umwmz?file=/pages/index.vue:70-100

Surt commented 2 years ago

The problem with that is that options.components only list the "loaded" ones. I can't see how to check if the component can be autoloaded before the :is to provide a "fallback" component in case the one I'm looking for does not exists (dinamic component name based on options)

vhoyer commented 2 years ago

What about this but using vue 3?

Rigo-m commented 2 years ago

@vhoyer in vue3 you can use resolveComponent to check if a component exists. Nuxt/components is not needed in Nuxt3 since components gets auto-imported by the framework itself.