Programmatically create Vue components with TypeScript

Viewed 63

I found a few answers regarding programmatically creating vue components but none with TypeScript. My application has a mongodb in the backend where I store my data and an API layer build with Spring Boot. In one of my components, I have an API call to get the data from the backend and I would like to create components out of the response.

@Component
export default class LayoutEditor extends Vue {
    public elements: Element[];

    @Prop({type: String, required: true})
    private id: string;

    public created() {
        axios.get('template/layout/' + this.id).then((response) => {
            this.initElements(response.data.elements);
        });
    }

    private initElements(elements: any[]) {
        this.elements = [];
        elements.forEach((element: any) => {
            const elemInst: Element = Element.newInstance(element);
            this.elements.push(elemInst);
        });
    }
}

And in the template: <component v-for="(element) in elements" :is="element"></component>

It compiles and it doesn't throw runtime errors, but the components aren't rendered.

@Component
export default class Element extends Vue {

    public static newInstance(obj: any) {
        const element = new Element();
        element.id = ob.id;
        element.data = obj.data;
        return element;
    }

    public id: string;
    public data: any;

}

I tried to use the following pattern as well:

const ElementClass = Vue.extend(Element);
const element = new ElementClass();

But then I cannot set the id and data as the type is not Element but ExtendedVue.

So what is the proper way to achieve these dynamic components based on some backend data?

0 Answers
Related