I’m trying to dynamically append a VNode to a container on a click event from the user.
I was expecting the code below to append a new child to the container div each time the button is clicked but what’s happening is that upon each click the previous child is replaced by the new one inside the div as the following gif illustrates.
How could I following the same concept, of dynamically creating VNodes, achieve the outcome of appending a node without replacing the previous one?
import {defineComponent, h, createVNode, render} from "vue";
export default defineComponent({
setup() {
return () => {
const container = h('div', []);
const button = h('button', {
onClick: () => {
const node = createVNode('div', null,[`Time: ${new Date().toISOString()}`]);
node.appContext = container.appContext;
render(node, container.el as any);
}
}, ['Add New'])
container.children?.push(button);
return container;
};
}
})
(For reference I’ve followed this tutorial)
Thank you for your time
With
render(node, container.el as any);you replace the inner HTML of yourdivcontainer every time with the new created node. This approach is questioned. Since:I would just use Vue reactivity instead of rendering new
vnodes.Or even do it much simpler, like this