我有一个父组件,它包装多个子“child”。我希望父级本质上具有与普通标记相同的模板,这就是我使用渲染函数的原因。
我希望父级能够管理哪个子级处于事件状态。但这些 Prop 似乎并没有传递给 children 。
我尝试过应用 documentation says ,但子项上的 props 未定义。但是,如果我这样做 item.data.staticClass = 'testing-class';
该类适用于每个 child 。
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
最佳答案
首先,我认为 this.$props
将始终是未定义的。 $props
属性可以在 {{ $props }}
这样的模板中访问,但那些内联属性(令人沮丧)并不总是直接映射到 this
变量在组件的脚本中可用。您可以使用 this.$options.propsData
查看组件的 prop 值。
其次,您可以使用item.componentOptions.propsData
来设置子组件的属性值。 (我认为 item.data.props
是引用其他内容的用词不当)。 Here's a fiddle with the change.
关于javascript - VueJS 在渲染函数调用中将 props 传递给子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42764535/