Can Vue components be loaded at runtime, after I initialize my application? Well, the answer is yes, but it is not the most common scenario.
Consider a scenario in which you have a large application and user may not need to access all its functionality every single time. For instance, you do not expect your users to unsubscribe from your web application every single time (one unsubscribe and they are gone for ever). So, it makes sense for any feature that is not used on a regular basis, to be load on demand.
Here is the logic:
- Load your application the same you typically do
- Load the deferred component (e.g. jQuery.load(selector, callback)
- Create an instance of your component
- Mount it
- Attach it to your app
Component code
<template id="aha">
<div class="aha position-absolute">
<h1>Hello, %{name}</h1>
</div>
</template>
<script type="text/javascript">
var aha = Vue.component('aha', {
delimiters: ['%{', '}'],
data: function () {
return {
name: 'Raul'
}
},
template: document.querySelector('#aha')
});
</script>
<style type="text/css">
.aha {
color: red;
font: 40px;
}
</style>
Loader code
$('#container').load('/path/to/component', function() {
var instance = new aha();
instance.$mount();
app.$el.appendChild(instance.$el);
// OR
// app.$refs.container.appendChild(instance.$el);
});