2017-03-13 51 views
1

我有一個包含多個孩子'孩子'的父組件。我希望父母基本上具有與香草標記相同的模板,這就是爲什麼我使用渲染功能的原因。VueJS將道具傳遞給渲染函數調用中的兒童

我希望父母管理孩子活躍的狀態。但道具似乎並沒有傳遞給孩子們。

我已經嘗試過應用什麼documentation says,但道具在兒童身上沒有定義。但是,如果我做item.data.staticClass = 'testing-class';該類適用於每個孩子。

Vue.component('parent', { 
    data: function() { 
    return { 
     activeIndex: 0 
    } 
    }, 
    render: function(createElement) { 
    this.$options._renderChildren.forEach(function(item, index) { 
     if (item.data === undefined) //whitespace? 
     return; 

     item.data.props = { 
     activeindex: this.activeIndex, 
     index: index 
     } 
    }.bind(this)); 

    return createElement('div', {}, this.$options._renderChildren); 
    } 
}); 

Vue.component('child', { 
    template: '<div>Im a child</div>', 
    props: ['activeindex', 'index'], 
    mounted: function() { 
    console.log(this.$props); //undefined 
    } 
}); 

new Vue({ 
    el: '#app' 
}); 

JSFIDDLE DEMO

回答

1

首先,我認爲this.$props將永遠是不確定的。可以使用{{ $props }}等模板訪問$props屬性,但這些內聯屬性(令人沮喪)並不總是直接映射到組件腳本中可用的this變量。您可以使用this.$options.propsData查看組件的prop值。

其次,您可以使用item.componentOptions.propsData來設置子組件的屬性值。 (我認爲item.data.props是引用其他內容的用詞不當)。 Here's a fiddle with the change.

+0

感謝您花時間協助。我實際上意識到這一點,但沒有時間發佈答案,因爲它導致了更多與父母/孩子交流的問題! EG:https://jsfiddle.net/zqufydvc/1/ – Kiee

相關問題