Load component dynamically based on url parameters in nuxt
I found a solution to this yesterday. It needs to be done like this.
<template>
<div>
<h1>{{myData.header}}</h1>
<p>{{myData.text}}</p>
<component :is="componentInstance"></component>
</div>
</template>
<script>
export default {
computed: {
componentInstance () {
const name = this.myData.component
return () => import(`./components/${name}`)
}
},
async asyncData(context) {
return {
myData: context.params.myData
}
}
}
</script>
More info in this article: https://itnext.io/vue-a-pattern-for-idiomatic-performant-component-registration-you-might-not-know-about-9f3c091846f5.
Based on Imre_G's answer, it can be simplified like this:
<template>
<div>
<h1>Hi</h1>
<p>Hello World!</p>
<Component :is="component"></Component>
</div>
</template>
<script>
export default {
computed: {
component() {
return () =>
import(`../../__relative_path__/${this.$route.params.yourParam}`)
}
}
}
</script>