Senči
Senči

Reputation: 941

Is it possible to exchange the render functions of VueJS-Components during runtime?

I've played around with vue-i18n and Vue.compile() and found a very static solution to my problem. While searching for a solution I've tried to dynamically set the render functions during runtime. Unfortunately without any success.

Out of curiosity: Is it possible to exchange the render functions of Components during runtime?

I try to do something like this:

{
    props: {
        toCompile: {
            type: String,
            required: true
        },
        callbackFn: {
            type: Function,
            default: () => {}
        }
    },
    created (){
        let res = Vue.compile(this.toCompile);
        this.render = res.render;
        this.staticRenderFns = res.staticRenderFns;
    }
}

Upvotes: 1

Views: 255

Answers (1)

Pascal Poschenrieder
Pascal Poschenrieder

Reputation: 31

The following approach is working for me:

{
   ...
    methods: {
        render: function () {
            var createElement = this.$createElement;
            return (this._self._c || createElement)("div", {
                staticClass: "element"
            });
        }
    },
    beforeCreate: function() {
        this.$vnode.componentOptions.Ctor.options.render = this.$vnode.componentOptions.Ctor.options.methods.render.bind(this);
    }
}

If your want slots as well, use the following render method:

        render: function () {
            var that = this,
                createElement = (this._self._c || this.$createElement),
                children = Object.keys(that.$slots).map(function(slot) {
                    return createElement('template', { slot }, that.$slots[slot]);
                });
            return createElement('div', [
                createElement('component-element, {
                    attrs: that.$attrs,
                    on: that.$listeners,
                    scopedSlots: that.$scopedSlots,
                }, children)
            ]);
        }

Upvotes: 1

Related Questions