Vue中的solt插槽

一、概念:

插槽就是父组件往子组件中插入一些内容。

二、插槽的种类:

有三种方式,默认插槽,具名插槽,作用域插槽

  1. 默认插槽就是把父组件中的数据,显示在子组件中,子组件通过一个slot插槽标签显示父组件中的数据

单个slot (默认插槽 或 匿名插槽)

就是没有名字的插槽,一个组件里面只允许存在一个匿名插槽。

    <div class="fa">
        <h1>父组件</h1>
        <child>
           <p>父组件中写的文本</p>
        </child>
    </div>
    

子组件内容

  • 父组件在child子组件中放置p标签,子组件中想要显示p标签,就必须放置slot

	<div class="child">
	 	<h2>子组件</h2>
	    <slot>匿名插槽的默认内容</slot>
	</div>

编译结果如下:

child组件slot里的内容会替换成 p标签里面的内容,如果父组件没有在子组件插入内容则会渲染slot里面的默认内容。

     2. 具名插槽是在父组件中通过slot属性,给插槽命名,在子组件中通过slot标签,根据定义好的        名字填充到对应的位置。

父组件:

	
	<div class="fa">
		<h1>父组件</h1>
		<child>
			<div class="son" slot="s1">
				<span>111</span>
			</div>
			<div class="son" slot="s2">
				<span>222</span>
			</div>
			<-- 以下是多余的内容,将会自动填充到匿名插槽中-->
			<div class="son">
				<span>333</span>
			</div>
		</child>
	</div>
	

子组件:

	
	<div class="child">
		<h2>子组件</h2>
		// s1插槽
		<slot name="s1"></slot>
		// s2插槽
		<slot name="s2"></slot>
		// 匿名插槽
		<slot></slot>
	</div>
	

具名插槽的缩写方式

           以#号形式加上插槽名称

	
	<div class="fa">
		<h1>父组件</h1>
		<child>
			<div class="son" #s1>
				...
			</div>
		</child>
	</div>
	

     3.作用域插槽是带数据的插槽,子组件提供给父组件的参数,父组件根据子组件传过来的插槽         数据来进行不同的展现和填充内容。在标签中通过slot-scope来接受数据。

  
    <div class="fa">
        <h1>父组件</h1>
		<child >
		    <template v-slot="props">
		        {{props.item}}
		    </template>
		</child>
    </div>
    
    

    
   

注意点1:在Vue 2.6+中,如果只存在默认插槽,可以用以上简写法 ,否则必须完整书写: v-slot:default=“props”
注意点2:在Vue 2.6+ 引入了v-slot 指令,在接下来所有的 2.x 版本中 slot 和 slot-scope 还可以使用,但不会出现在 Vue 3.0 中,详细的内容自己查阅官方文档吧。

子组件内容


<template>
	<div class="child">
	 	<h2>子组件</h2>
        <ul>
            <li v-for="item of arr" >
            	<slot :item="item"></slot>
            </li>
        </ul>
	</div>
<template/>
<scirpt>
  data(){
        return {
            arr:[111, 222, 333]
        }
    }
<scirpt/>

总结

v-slot的出现是为了代替原有的slot和slot-scope
简化了一些复杂的语法。
一句话概括就是v-slot :后边是插槽名称=后边是组件内部绑定作用域值的映射

 

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值