[solved] re-mount & render App + child components after DOM "destruction" by (external) .innerHTML #1476
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ok, so the solution was annoyingly simple. Since Vue can't/won't tell it lost its connection to the real DOM, using a MutationObserver is key to the solution. The When the MutationObserver's handler is called, all you need to do is put the app's element back into the DOM, replacing the new but vanilla DOM element that was created due to the Here are the essential bits in the application code (or index.js) that need customizing for the element ids. data() {
observer: undefined
},
methods: {
observe(mutationList, observer) {
// on the initial page load the MO might trigger, but nothing was removed yet
if ( !mutationList[0].removedNodes.length ) {
return;
}
// disable the observer
this.observer.disconnect();
// put the App's $el back into the LIVE DOM where the new #app sits
let elt = document.getElementById('content');
elt.querySelector('#myapp').replaceWith( this.$el );
// start observing for the next DOM attack
this.observer.observe(elt, {childList: true, subtree: true}); // adjust options to your situation
}
},
mounted() {
let elt = document.getElementById('content')
this.observer = new MutationObserver(this.observe);
this.observer.observe(elt, {childList: true, subtree: true});
},
// if you tear down the app programmatically, make sure to also
// disconnect and release the MutationObserver from its duty. Not only are all the event handlers intact, the state of each child component is exactly as it was when the DOM was ripped apart. Hope this helps anyone who happens to have the same bizarre problem. |
Beta Was this translation helpful? Give feedback.
Ok, so the solution was annoyingly simple.
Since Vue can't/won't tell it lost its connection to the real DOM, using a MutationObserver is key to the solution.
The
$el
property of each component is still holding a fully functional copy of the "original" element in its rendered state incl. all the children, read: their connection to the actual document might be broken, but it's still intact within the "subtree" owned by the application's top level$el
.When the MutationObserver's handler is called, all you need to do is put the app's element back into the DOM, replacing the new but vanilla DOM element that was created due to the
innerHTML
result.Here are the essential bits in the applicati…