VueJS 在渲染函数调用中将道具传递给 children
VueJS pass props to children in render function call
我有一个包含多个 children 'child' 的 parent 组件。我希望 parent 本质上具有与原始标记相同的模板,这就是我使用渲染函数的原因。
我希望 parent 管理 child 处于活动状态的状态。但是这些道具似乎并没有传给 children.
我已经尝试应用 documentation says,但是 children 上的道具未定义。但是,如果我执行 item.data.staticClass = 'testing-class';
,则 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'
});
首先,我认为 this.$props
永远是未定义的。 $props
属性 可以在像 {{ $props }}
这样的模板中访问,但是那些内联属性(令人沮丧)并不总是直接映射到组件脚本中可用的 this
变量.您可以使用 this.$options.propsData
.
查看组件的属性值
其次,您可以使用item.componentOptions.propsData
设置子组件的属性值。 (我认为 item.data.props
是引用其他东西的用词不当)。 Here's a fiddle with the change.
我有一个包含多个 children 'child' 的 parent 组件。我希望 parent 本质上具有与原始标记相同的模板,这就是我使用渲染函数的原因。
我希望 parent 管理 child 处于活动状态的状态。但是这些道具似乎并没有传给 children.
我已经尝试应用 documentation says,但是 children 上的道具未定义。但是,如果我执行 item.data.staticClass = 'testing-class';
,则 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'
});
首先,我认为 this.$props
永远是未定义的。 $props
属性 可以在像 {{ $props }}
这样的模板中访问,但是那些内联属性(令人沮丧)并不总是直接映射到组件脚本中可用的 this
变量.您可以使用 this.$options.propsData
.
其次,您可以使用item.componentOptions.propsData
设置子组件的属性值。 (我认为 item.data.props
是引用其他东西的用词不当)。 Here's a fiddle with the change.