I'm currently working on a third party app, using Vue to render components.
The third party application loads the component dynamically after Vue app is intialized and mounted. As a result, I could only see the HTML of the component, but not actually the template that is inteded to be rendered. Meaning, I could see something like <my-component></my-component> when I inspect, but not the template of the myComponent.
Here is an example of the challenge I'm mentioning about https://jsfiddle.net/EmeraldCodeNinja/31jkmzgc/12/. In this example, you will find a button, clicking on which appends vue component to the DOM using JavaScript.
Please suggest a way to make this work, so I can render dynamically added component.
Note: The intention is not to make the JSFiddle work, it is just an example simulating the challenge I'm facing. My intention is to make the dynamically added vue-component to render.
Posting the same HTML and JS from the JSFiddle
HTML
<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
<div id="app">
<sample-button></sample-button>
<div id="new-button-wrap"></div>
</div>
<script id="sample-button" type="text/html">
<button @click="addNew">Add Another Sample Button</button>
</script>
JS
const app = Vue.createApp();
app.component('sample-button', {
template: '#sample-button',
setup() {
const addNew = function() {
var div = document.createElement('div');
var sampleBtn = document.createElement('sample-button');
div.textContent = 'here a button should appear, but instead a tag is appearing'
div.appendChild(sampleBtn)
document.querySelector('#new-button-wrap').appendChild(div)
}
return {
addNew
}
}
})
app.mount('#app');
You can create a Vue instance in run-time using createApp and mount methods to append it to the DOM.
createApp({
template: "<button id=`button`>I'm a button!</button>",
}).mount(document.getElementById("button-container"));
Here is the CodeSandbox link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With