vue插槽(slot)的模板與JSX寫法


vue官網API:

插槽:https://cn.vuejs.org/v2/guide/components-slots.html

JSX:https://cn.vuejs.org/v2/guide/render-function.html

說明:vue版本2.6.0以上語法

一、插槽模板傳值

子組件:child.vue

<template>
    <div>
        <!-- 默認插槽 -->
        <slot :info="info"></slot>
        <!-- other插槽 -->
        <slot name="other" :info="info2"></slot>
    </div>
</template>

<script>
export default {
    data() {
        return {
            info: {
                title: "標題一"
            },
            info2: {
                title: "標題二"
            }
        };
    }
};
</script>

父組件:parent.vue

<child>
    <template v-slot:default="slotProps">
        <div>
            {{ slotProps.info.title }}
        </div>
    </template>
    <template v-slot:other="slotProps">
        <div>
            {{ slotProps.info.title }}
        </div>
    </template>
</child>

結果:

 

 

 二、插槽傳值JSX寫法

子組件:child.jsx

export default {
    data() {
        return {
            info: {
                title: "標題一"
            },
            info2: {
                title: "標題二"
            }
        };
    },
    render() {
        return (
            <div>
                {this.$scopedSlots.default({
                    info: this.info
                })}

                {this.$scopedSlots.other({
                    info: this.info2
                })}
            </div>
        );
    }
};

父組件:parent.jsx

<child
    scopedSlots={{
        default: props => {
            return (
                <div style="line-height: 30px;">
                    {props.info.title}
                </div>
            );
        },
        other: props => {
            return (
                <div style="line-height: 30px;">
                    {props.info.title}
                </div>
            );
        }
    }}
/>

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM