Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass slots to a programatically created vuejs component instance

My app requires creating dynamic component instances, for which I am using the following method:

import Button from 'Button.vue'
...
var Ctor = Vue.extend(Button);
var instance = new Ctor({ propsData: {} });
instance.$mount('#el');

All this works fine, I am able to pass props too. But now I need to pass slots to that instance too. I have tried random unsuccessful things like:

var instance = new Ctor({ propsData: {}, slots: { default: someNode }});

I have searched everywhere and have no clue if that is even possible or not. Any pointers?

like image 610
Kushagra Gour Avatar asked Oct 18 '25 03:10

Kushagra Gour


2 Answers

From How to create Vue.js slot programatically?

I looked into TypeScript definition files of Vue.js and I found an undocumented function on Vue component instance: $createElement(). My guess is, it is the same function that is passed to render(createElement) function of the component. So, I am able to solve it as:

const Constr = Vue.extend(MyComponent);
const instance = new Constr({
    propsData: { someProp: 'My Heading' }
});

// Creating simple slot
const node = instance.$createElement('div', ['Hello']);
instance.$slots.default = [node];

instance.$mount(body);

But this is clearly undocumented and hence questionable approach. I will not mark it answered if there is some better approach available.

like image 139
Lukas Avatar answered Oct 21 '25 08:10

Lukas


Slots can be set on the created instance by manipulating the $slots key:

import Button from 'Button.vue'
...
var ButtonConstructor = Vue.extend(Button);
var instance = new ButtonConstructor({ propsData: {} });

// SET SLOT
instance.$slots.default = [ 'Hello' ];

instance.$mount('#el');
like image 23
Kushagra Gour Avatar answered Oct 21 '25 08:10

Kushagra Gour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!