In this article, I will show how to mount Vue components programmatically, and how you can use this technique for nesting Vue components and externally managed DOM elements.
I'm using the Vue.js front-end framework in many of my projects. It is easy to learn, well documented, and the "single-file-component" architecture (.vue files) makes it easy to create and maintain reusable components.
Within a Vue component, all DOM elements are managed by Vue: New elements are added to or removed from the DOM tree as needed.
In this simple example a new h1 element is created or removed again as soon as the button is pressed.
Sometimes it can be necessary to include a DOM element that is managed by external code (e.g. a third party library) which is not designed to be used with with Vue:
<template>
<my-component>
<div class="dom-element-from-external-library">
<h1>Hello from external library</h1>
</div>
</my-component>
</template>
In Vue it is possible to use the lifecycle hooks (mounted(), updated(), beforeDestroy()) and the $el and $ref properties to sync external code with the lifecycle of a Vue component.
An Beispiel:
Sometimes it may be necessary to create a child element in a Vue component via external library, which in turn should have another Vue component as child element:
<template>
<my-component>
<div class="dom-element-from-external-library">
<h1>Hello from external library</h1>
<my-other-component />
</div>
</my-component>
</template>
The implentation of this structure is a bit more complex. However, with a simple helper function it is possible to mount Vue components programmatically in any parent element.
I took the mountComponent function from pearofducks github and adapted it slightly.