vue-slot插槽

作用:让父组件可以向子组件中任意位置插入html结构,也是组件通信方式的一种,适用于父组件===》子组件
分类: 默认插槽、具名插槽、作用域插槽
定义子组件时使用slot组件,在使用子组件是可以决定是否插入具体的html代码

默认插槽

如果在使用子组件插入具体的html代码,那么slot中就会替换成对应的内容
如果使用时没有出入具体的html代码,那么就会使用slot中默认定义的内容

案例1-使用组件有内容

    <!-- 子组件 -->
    <template id="page">
        <div>
            <h1>头部导航栏</h1>

            <p>
                <slot>我是默认内容</slot>
            </p>

            <h1>底部导航栏</h2>
        </div>
    </template>

    <!-- 父组件 -->
        <alert-com>
            <p>我是父组件中定义的内容</p>
        </alert-com>
   
      Vue.component('alert-com',{
        template:'#page',
    })

在这里插入图片描述

案例2-使用组件无内容

 <!-- 子组件 -->
    <template id="page">
        <div>
            <h1>头部导航栏</h1>

            <p>
                <slot>我是默认内容</slot>
            </p>

            <h1>底部导航栏</h2>
        </div>
    </template>
 
  <!-- 父组件 -->
     <alert-com1 ></alert-com1>
     
    Vue.component('alert-com1',{
        template:'#page',
    })

在这里插入图片描述

具名插槽

在定义子组件时可以定义很多slot插槽,并且可以命名。在父组件中使用子组件可以使用slot="center"使用命名可以来选择对应插槽的部分和内容

案例

父组件中:
        <Category>
            <template slot="center">
              <div>html结构1</div>
            </template>

            <template v-slot:footer>
               <div>html结构2</div>
            </template>
        </Category>
子组件中:
        <template>
            <div>
               <!-- 定义插槽 -->
               <slot name="center">插槽默认内容...</slot>
               <slot name="footer">插槽默认内容...</slot>
            </div>
        </template>

作用域插槽

数据在组件自身(子组件),但是数据的生成结构由组件使用者(父组件决定)
(games数据在Category(子)组件中,但使用数据所遍历出来的结构由App(父)组件决定)
由案例可知子组件传值给父组件,子组件中可以通过slot-scope =‘xxx’ (简写 scope=‘xxx’)把数据接收到xxx的对象中

案例

父组件中:
		<Category>
			<template scope="scopeData">
				<!-- 生成的是ul列表 -->
				<ul>
					<li v-for="g in scopeData.games" :key="g">{{g}}</li>
				</ul>
			</template>
		</Category>

		<Category>
			<template slot-scope="scopeData">
				<!-- 生成的是h4标题 -->
				<h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
			</template>
		</Category>
子组件中:
        <template>
            <div>
            <!-- 通过数据绑定就可以把子组件的数据传到父组件 -->
                <slot :games="games"></slot>
            </div>
        </template>
		
        <script>
            export default {
                name:'Category',
                props:['title'],
                //数据在子组件自身
                data() {
                    return {
                        games:['红色警戒','穿越火线','劲舞团','超级玛丽']
                    }
                },
            }
        </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值