Using VueJS computed properties for dynamic module imports

Displaying Components

Dynamic Component

<component :is="componentType"></component>
<template>
<div class="componentWrapper">
<component :is="componentType">
</component>
</div>
</template>
<script>
export default {
name: 'component-wrapper',
props: {
componentType: {
type: String,
default: () => null
}
}
}
</script>

Dynamic Module Imports

<template>
<div class="componentWrapper">
<component :is="componentLoader">
</component>
</div>
</template>
<script>
export default {
name: 'component-wrapper',
props: {
componentFile: {
type: String,
default: () => null
}
},
computed: {
componentLoader () {
return () => import('./${this.componentFile}
}
}
}
</script>

The Promise

<template>
<div class="componentWrapper">
<component :is="componentLoader" :options="options">
{{ this.$props.slot }}
</component>
</div>
</template>
<script>
export default {
name: 'component-wrapper',
props: {
componentFile: {
type: String,
default: () => null
},
options {
type: Array,
default: () => []
},
slot: {
type: String,
default: () => null
}
},
mounted () {
if (this.$props.componentFile) {
loadComponent()
}
},
computed: {
componentLoader () {
return () => import('./${this.componentFile}
}
},
methods: {
loadComponent () {
this.componentLoader().then(comp => {
console.log(comp.data)
})
}
}
}
</script>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alex Scott

Alex Scott

109 Followers

PHP & JavaScript focused developer, mainly using Laravel & Vue.JS, I develop most projects under the alias @codetheorist