Vue's method of passing slots across layers

Because of business needs, our vue components are divided into many layers. But I need to specify the template through the slot in the parent component, but not render it in the child component, but render it in the grandchild component or the component below it.

For example, I have a generic A component, the A component references the B component, and the B component references the C component. A part of the template of the C component needs to be configured in the A component.

Because there are more than 1 layer of components in the middle, it cannot be solved by the general slot method. So I studied the scoped-slots of vue, and felt that the design of vue is really flexible and can be easily implemented.

 

1. First, the template of the A component:

<div>
    ...
    <span slot="nodeMenu" slot-scope="{node}">{{node.text}}</span>
    ...
</div>

 

2.1. If the B component is a template method, the template of the B component:

<div>
    ...
        <span slot="nodeMenu" slot-scope="{node}">
            <slot name="nodeMenu" :node="node"></slot>
        </span>
    ...
</div>

2.2. If the B component is rendered by the render script, it can be as follows:

render(h){
    return h(ComponentC, {
        props: {
            ...
        },
        scopedSlots: self.$scopedSlots,
        on: {
           ...
        }
    })
}

 

3. Template of C:

<div v-for="treeNode in nodes">
    ...
    <slot name="nodeMenu" :node="treeNode"></slot>
    ...
</div>

 

 

By analyzing the Vue source code, Vue's scopedSlots are rendering functions (not VNodes). Passing a C component through these functions in the B component realizes the cross-layer transfer of slots.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324893163&siteId=291194637