My goal is to dynamically add components to a page in my Vue Single file Component by receiving component information via JSON. While this process works smoothly if the components are known in advance, I faced challenges when trying to create them dynamically. Below, you can see my attempt to use eval, which unfortunately does not work with uninstantiated objects. The code snippet provided below uses hardcoded values for illustration purpose.
<template>
<div id="app">
<h2>Static template:</h2>
<InputTemplate type="text"></InputTemplate>
<h2>Dynamically inserted:</h2>
<div ref="container">
<button @click="onClick">Click to insert</button>
<br/>
</div>
</div>
</template>
<script>
import Vue from 'vue'
//the component I'd like to create
import InputTemplate from './components/InputTemplate.vue'
export default {
name: 'app',
components: { InputTemplate },
methods: {
onClick() {
//I'd like to do something like this, but eval doesn't work like this
var ComponentClass = Vue.extend(eval('InputTemplate'))
var instance = new ComponentClass({
propsData: {type: 'text' }
})
instance.$mount()
this.$refs.container.appendChild(instance.$el)
}
}
}
</script>
<p>To overcome the limitations of eval, I created a helper function that eliminates the need for manual upkeep of new components being added. Although functional, it feels a bit inelegant. Is there a more efficient approach to achieve this?</p>
<pre><code>returnComponent(componentString){
if(componentString === 'InputTemplate'){
return InputTemplate;
}
}