If I have a component with a single slot and instead of simply rendering all its children, I want to wrap each element individually, the following approach can be taken:
Vue.component('MyElement', {
render: function(createElement){
for (let i = 0; i < this.$slots.default.length; i++) {
// Create a wrapper element
let wrappedElement = createElement("div", {}, this.$slots.default[i]);
// Replace the current element in this slot with the wrapped element
this.$slots.default[i] = wrappedElement;
}
return createElement("div", this.$slots.default);
}
}
Usage example:
<MyElement ref="myElement">
<p>Item 1</p>
<p>Item 2</p>
</MyElement>
Resulting in the following structure:
<div>
<div>
<p>Item 1</p>
</div>
<div>
<p>Item 2</p>
</div>
</div>
So far, everything works as intended.
However, when attempting to dynamically insert another <p>
element into <MyElement>
using
// Get reference to <MyElement>
const myElement = this.$refs["myElement"];
// Create a new element
var newElement = document.createElement("div");
newElement.innerText = "Hiya";
myElement .$el.appendChild(newElement);
The new element will not be wrapped because the render method is not invoked again. Is there a way to take full control of rendering for each child in the slot or perhaps a better method to programmatically append children into a component?
Thank you.