VueJS在渲染函数调用中将子句传递给子节点 [英] VueJS pass props to children in render function call

查看:172
本文介绍了VueJS在渲染函数调用中将子句传递给子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个孩子'child'的父组件。我希望父级基本上具有与vanilla标记相同的模板,这就是我使用render函数的原因。

I have a parent component that wraps multiple children 'child'. I want the parent to essentially have the same template as the vanilla markup which is why I am using the render function.

我希望父级管理哪个子级的状态活跃。但道具似乎没有传给孩子们。

I want the parent to manage the state of which child is active. But the props don't appear to be passing down to the children.

我尝试应用 文档说 ,但是孩子们的道具未定义。但是,如果我 item.data.staticClass ='testing-class'; 该类适用于每个孩子。

I have tried applying what the documentation says, but props are undefined on the children. However if I do item.data.staticClass = 'testing-class'; that class applies to each 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

JSFIDDLE DEMO

推荐答案

首先,我认为 this。$ props 将始终未定义。可以在 {{$ props}} 等模板中访问 $ props 属性,但这些内联属性(令人沮丧)并不总是直接映射到组件脚本中可用的变量。您可以使用来查看组件的prop值。$ options.propsData

First of all, I think that this.$props will always be undefined. The $props property is accessible in a template like {{ $props }}, but those inline properties (frustratingly) don't always map up directly to the this variable available in the component's script. You can see the component's prop values using this.$options.propsData.

其次,您可以使用 item.componentOptions.propsData 设置子组件的属性值。 (我认为 item.data.props 是一个用词不当引用别的东西)。 这里有一个改变的小提琴。

Secondly, you can use item.componentOptions.propsData to set the property values of the child component. (I think item.data.props is a misnomer referencing something else). Here's a fiddle with the change.

这篇关于VueJS在渲染函数调用中将子句传递给子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆