在vue中将插槽递归地传递到自引用节点

时间:2019-06-22 11:45:34

标签: typescript vue.js

我使用name属性创建了如下的自引用组件。 它正在使用插槽。我也需要传递给子节点。我已经如下循环了子节点。

<template>
  <div>
    <slot name="filters"></slot>
    <template v-if="node.children && node.children.length">
      <node v-for="child in node.children" :node="child">
      </node>
    </template>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';

@Component({
  name: 'node',
})
export default class TreeNode extends Vue {

  @Prop({ default: [] })
  public node: any;
}
</script>

我正在如下使用它。

<node-tree :node="treeData">
  <template v-slot:filters>
    <h1>Here might be a node content</h1>
  </template>
</node-tree>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import NodeTree from './TreeNode.vue';

@Component({
  components: {
    NodeTree,
  }})
export default class Tree extends Vue {

  //TODO: Following data is only for demo. Remove it. and set appropriate.
  public treeData = {
    label: 'A cool folder',
    children: [
      {
        label: 'A cool sub-folder 1',
        children: [
          { label: 'A cool sub-sub-folder 1' },
          { label: 'A cool sub-sub-folder 2' },
        ],
      },
      { label: 'This one is not that cool' },
    ],
  };
}
</script>

但是子节点未显示插槽内容。如何递归传递它们。

1 个答案:

答案 0 :(得分:0)

关注treenode对我有用

<template v-if="node.children && node.children.length">
          <node v-for="child in node.children" :node="child">
            <template v-for="(_, slot) in $slots">
              <template :slot="slot">
                <slot :name="slot"></slot>
              </template>
            </template>
          </node>
        </template>