vue 插槽学习总结

插槽:子组件中提供给父组件使用的一个占位符
父组件可以在这个占位符中填充任何代码
示例主要是官网例子和自己写的简洁例子结合

1.默认插槽

父组件

<template>
    <div id="app">
        <test>我是父组件</test>
    </div>
</template>

子组件test

<template>
    <div>
        我是子组件
        <slot>我是后备内容</slot>
    </div>
</template>

当子组件内有<slot></slot>时,父组件引用子组件内部的“父组件”三个字才会起作用。slot为父组件提供了一个子组件的占位符。
先渲染子组件,后渲染父组件
2.后备内容
当父组件不提供任何插槽内容时,才会渲染子组件内与中间的后备内容。
如下:

父组件中

<template>
    <div id="app">
        <test></test>
    </div>
</template>

渲染后的页面如下:
在这里插入图片描述
3.具名插槽
插槽具有名字后,可以通过插槽名字来控制插槽的显示与否。

父组件

<template>
    <test>
        <template name ="header">
            <h1>Here might be a page title</h1>
        </template>

        <p>A paragraph for the main content.</p>
        <p>And another one.</p>

        <template name ="footer">
            <p>Here's some contact info</p>
        </template>
    </test>
</template>

子组件

<template>
    <div class="container">
        <header>
            <slot slot-scope ="header"></slot>
        </header>
        <main>
            <slot></slot>
        </main>
        <footer>
            <slot slot-scope ="header"></slot>
        </footer>
    </div>
</template>

4.作用域插槽
父组件绑定了子组件后,子组件可以在slot标签上绑定属性值,简单来讲就是在子组件的插槽上绑定了数据
子组件

<template>
    <div class="child">

        <h3>子组件</h3>
        <slot :data="data"></slot>
    </div>
</template>

<script>
    export default {
        name: "test",
        data(){
            return {
                data: ['1','2','3','4','5','6']
            }
        }
    }
</script>

父组件

        <child>
            <template slot-scope="user">
                <ul>
                    <li v-for="item in user.data">{{item}}</li>
                </ul>
            </template>
        </child>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值