You have opted for a challenging approach in solving the requirement. The main issue lies in the content of the string, which is essentially a Vue SFC (.vue
file). Converting this SFC into a usable Vue component in the browser requires several steps. You need to utilize tools like Webpack (or Rollup), integrate vue-loader for parsing the SFC, and apply different Webpack loaders to handle each section of the SFC (such as Babel for transpiling the <scipt>
block, sass-loader and sass compiler for converting
<style lang="scss">
into CSS)
While there are browser-based tools available for some of these tasks (like vue3-sfc-loader), they come with significant drawbacks - for instance, vue3-sfc-loader adds approximately 1.4MB of minified JavaScript to your project. This additional weight can impact performance significantly.
An easier alternative is to leverage standard tooling at build time
- Create your components as usual, within
.vue
files
- Utilize your components as Async Components and compile a list of available components. These components will be built into separate JavaScript files during compilation and loaded on-demand in the browser
// ComponentStore.js
export default {
component1: () => import('./components/component1'),
component2: () => import('./components/component2'),
}
Note: Automation tools can streamline the process of creating this component dictionary. For example, check out this reference
- Implement the component as a dynamic component
// DynamicComponent.vue
<template>
<component :is="comp" />
</template>
<script>
import ComponentStore from "ComponentStore.js"
export default {
props: ['componentName'],
computed: {
comp() {
return ComponentStore[this.componentName]
}
}
}
</script>