3

I have been working with creating vue components dynamically. But I am stuck with slot usage of dynamic vue components. Components assigned in slots reset when their parent's properties change.

Posted two sandbox

The first one is working. When you click "click to create" button it create a Text component inside slot of Button component. Then change values inside the textboxes and click the "hi" button. You will see that the data of button is changed and text boxes do not lose their values.

But in the second example, when you click the "hi" button after changing values, you will see that the text boxes lose their values (or resets to initial).

//Create Text inst.
var txt = new Text({
  parent: this,
  propsData: { text1: "hi internal" }
});
txt.$mount();
txt.$forceUpdate();

//Create Button inst.
var btn = new Button({
  parent: this,
  propsData: { type: "primary", text: "hi" }
});

//add eventHandler calling a method to change its prop.
btn.$on("test", () => btn.setText("a" + counter++));

//assign Text inst. to slot of Button
btn.$slots.default = [txt._vnode];
btn.$slots.default.forEach(function(vNode, index) {
  vNode.key = index;
});
btn.$mount();
btn.$forceUpdate();

//Create table inst.
var tbl = new Table({
  parent: this,
  propsData: { name: "sir john" }
});

//assign Button inst to slot of Table
tbl.$slots.default = [btn._vnode];
tbl.$slots.default.forEach(function(vNode, index) {
  vNode.key = index;
});
tbl.$mount();
tbl.$forceUpdate();

this.$refs.container.appendChild(tbl.$el);

For the solution I found a workaround, to see, you can uncomment the additional "div"'s inside the template of text component. (text.vue) Then the second example starts working.

I tried adding $forceUpdate and _vnode key assignments for slots, but none of them worked like div workaround.

Am I missing something here with dynamic vue component creation with slots ?

Alper Batıoğlu
  • 313
  • 1
  • 2
  • 9
  • is there any kind of profit considering this can be done by simply pushing an object with 4 properties or a so called state - doing it this way? – Estradiaz Sep 04 '19 at 21:10
  • If what you are suggesting is using a state object outside of components and components not having any properties, then these are reusable components used on different pages. Also I am using an existing component library which have their own properties, events and slots. – Alper Batıoğlu Sep 05 '19 at 06:18
  • Hmm, what i mean is this doesnt look like the way vue wants it - and what you experience is undefined behaviour - as the state of your txt instance is as expected but v-model defaults to a initial state ... just weird – Estradiaz Sep 05 '19 at 06:54

0 Answers0