[Vuejs]-VueJS pass prop to child without referencing child in parent template

0👍

The solution I have found is in the created function of the Parent component. Loop through the default slots and pass in an index to the Child VNode’s componentOptions.

The code below assumes only child components and whitespace are present in the template, you can add additional checks against each slot in the foreach to ensure it is the correct component.

created: function() {
        var index = 0;
        this.$slots.default.forEach(function(slot) {
            if (slot.componentOptions !== undefined && slot.componentOptions.propsData !== undefined) {
                slot.componentOptions.propsData.testProp = index;
                index++;
            }
        })
    },

Edit:
This however doesn’t have reactivity – you can’t data bind using this.

Leave a comment