I need to check for the existence of a component before dynamically displaying it in Nuxt. The component name is based on a route slug, therefore I can't know in advance if the component name is valid.
If there's no component for the slug, I would like to display a text using v-else. (see markup)
However, I'm not able to infer whether the component is available or not as return value is always a function.
<component :is="componentDynamic" v-if="componentDynamic" />
<h1 v-else>Component Not available</h1>
import Vue from 'vue'
export default Vue.extend({
computed: {
componentDynamic() {
const componentName = this.$route.params.slug,
const result = async () => await import(`@/components/${componentName}`)
console.log(result)
return result
},
},
})
Figured out if the component exists by trying to import it via import.
If the import errors out, the component is not available and an alternative message is shown.
<template>
<div>
<component
:is="componentName"
v-if="componentIsAvailable"
/>
<!-- Show if component doesn't exist -->
<div v-else>
<h1 class="text-5xl my-20">Component Not available</h1>
</div>
</div>
</template>
data() {
return {
componentIsAvailable: false,
componentName: this.$route.params.componentName // nuxt components are in PascalCase, so your parameter / slug should be as well
}
},
async fetch() {
const name = this.componentName
this.componentIsAvailable = await import(`@/components/${name}`)
.then((_res) => {
// console.log('result', _res)
return true
})
.catch((_error) => {
// console.log('error', _error)
return false
})
},