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:
In Vue it is possible to use the lifecycle hooks (
beforeDestroy()) and the
$ref properties to sync external code with the lifecycle of a Vue component.
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:
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.
Leave a comment
Replied on your own website? Send a Webmention!