【问题标题】:Does vuejs render function allow adopting an existing nested VNode of slotvuejs 渲染功能是否允许采用现有的嵌套 VNode 的插槽
【发布时间】:2022-01-09 14:52:12
【问题描述】:

我是 vuejs 渲染功能的新手,并且怀疑:可以重新采用 VNode,例如嵌套在插槽下的 VNode 被移动到另一个 VNode,如下例所示(仅用于演示目的, 与此版本不同):

以下代码

<row cols="4,8">
   <ui-text name="A" />
   <ui-text name="B" />
</row>

预计会产生与以下相同的结果:

<b-form-row>
   <b-col cols="4">
      <ui-text name="A" />
   </b-col>
   <b-col cols="8">
      <ui-text name="B" />
   </b-col>
</b-form-row>

这是我的代码,在 vuejs-devtools 视图中验证后最终输出与预期不完全相同,但 HTML 代码与预期结果相似。

vuejs-devtools中显示的结构,你可以发现2个UiText节点分别不是BCol节点的子节点,2个BCol节点被标记为功能,我不知道“功能”是什么,我不确定如何解决这种不一致,我的代码只是尝试让新创建的 VNode 采用现有的 VNode,我不确定 UiText 的 $parent 是否不可变,这是正确的解决方案吗?

export default {
  props: ['cols'],
  computed: {
    columns() {
      let v = this.cols;
      if (!v)
        return [];
      let values = this.cols.split(/,/g);
      return values;
    }
  },
  render: function(h) {
    let columns = this.columns;
    let children = this.$slots.default ? this.$slots.default : new Array();
    let kids = new Array();
    for(let i = 0, s = Math.min(columns.length, children.length); i < s; i++) {
      let kid = children[i];
      let node = h('b-col', {props: {cols: columns[i]}}, [ kid ]);
      kids.push(node);
    }
    return h('b-form-row', {}, kids);
  }
}

【问题讨论】:

    标签: vuejs2


    【解决方案1】:

    我误解了一些东西,功能组件就是这样工作的,所以没有问题。

    这是更新版本,也是一个功能组件。

    <script>
    
    export default {
      functional: true,
      props: ['cols'],
      render: function(h, ctx) {
        let columns = (ctx.props.cols  || '').split(/,/g);
        let children = ctx.children || new Array();
        let kids = new Array();
        for(let i = 0, s = Math.min(columns.length, children.length); i < s; i++) {
          let node = h('b-col', {props: {cols: columns[i]}}, [ children[i] ]);
          kids.push(node);
        }
        return h('b-form-row', {}, kids);
      }
    }
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 1970-01-01
      • 2021-08-31
      • 2020-05-19
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2021-04-16
      • 2022-12-29
      相关资源
      最近更新 更多