How to mount Vue components programmatically

Published by on

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.

Leave a comment

Available formatting commands

Use Markdown commands or their HTML equivalents to add simple formatting to your comment:

Text markup
*italic*, **bold**, ~~strikethrough~~, `code` and <mark>marked text</mark>.
Lists
- Unordered item 1
- Unordered list item 2
1. Ordered list item 1
2. Ordered list item 2
Quotations
> Quoted text
Code blocks
```
// A simple code block
```
```php
// Some PHP code
phpinfo();
```
Links
[Link text](https://example.com)
Full URLs are automatically converted into links.

Replied on your own website? Send a Webmention!