Adding custom directive to a slot in vuejs render function

Viewed 1146

I would like to create a renderless component which adds custom directive to it's root slot, and also encapsulates some behavior related to that directive.

I know I can use the createElement(), define directives as a part of its options, and get a VNode back. I also know that I have access to the slot in the render function via this.$slots.default[0]. This already holds a VNode in it, so I cannot pass it to the createElement() to add a directive. Next thing I know is that I can access the existing directives of a VNode through its properties (VNode.data.directives...).

Can I somehow combine all this to take a root slot, and add a directive to it without creating wrapper element? Any help / explanation is appreciated.

1 Answers

This worked for me.

export default {
    functional: true,
    render(h, ctx) {
        const slots = ctx.slots();
        const slot = slots.default[0];
        slot.data.directives = slot.data.directives || [];
        slot.data.directives.push({
            name: 'custom-directive',
        });
        return slot;
    },
};
Related