slot插槽二三事


前言

复习了下vue,感觉slot这块有点忘了,又捡起再复习了一下,又学到了一些新知识,在此记录。


一、slot是什么?

官方的解释是:

Vue 实现了一套内容分发的 API,这套 API 的设计灵感源自 Web Components 规范草案,将 slot 元素作为承载分发内容的出口。

这段话有点难理解,将用法总结出来可以归纳为以下几点:

  • 1.通过子组件插槽可以在双标签父组件内增加内容;
  • 2.子组件插槽内如果有内容,父组件内不写内容则默认显示子组件插槽内容;父组件内填写内容则将子组件插槽内容替换;
  • 3.可以自定义去替换哪些内容;
  • 4.可以将子组件数据向父组件内传递。

二、插槽分类

1.匿名插槽

即子组件只放置了没有名字的slot出口。

(1)当父组件标签内不写内容时:

子组件slotCom:

<template>
<div>
  <slot>我是默认内容</slot>
</div>
</template>

父组件:

<template>
<div>
  <slotCom></slotCom>
  </div>
</template>

结果:
在这里插入图片描述

(2)当父组件标签内填写内容时:

父组件:

<template>
<div>
  <slotCom>我是替换内容</slotCom>
  </div>
</template>

结果:
在这里插入图片描述
提示子组件只要设置了slot,父组件标签内就可以插任意多人内容。

2.具名插槽

即slot插槽有名字。

(1) 父组件内标签不指定替换内容:

子组件:

<template>
<div>
  <slot>我是默认内容</slot><br/>
  <slot name="a1">我是a1插槽里的内容</slot>
  </div>
</template>

父组件:

<template>
<div>
  <slotCom></slotCom>
  </div>
</template>

结果:
在这里插入图片描述
提示子组件内定义的多个slot都会在父组件标签内全部显示出来

(2)父组件内容指定替换内容:

官方提示:

在 2.6.0 中,我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。它取代了 slot 和slot-scope 这两个目前已被废弃但未被移除且仍在文档中的特性。新语法的由来可查阅这份 RFC。

父组件:

<template>
<div>
  <slotCom v-slot:a1>
      我是替换a1插槽的内容
  </slotCom>
  <!--    或者:-->
  <slotCom>
      <template v-slot:a1>
      我是替换a1插槽的内容
    </template>
  </slotCom>
</div>
</template>

不推荐:

  <slotCom>
      <template slot="a1">
      我是替换a1插槽的内容
    </template>
  </slotCom>

结果:
在这里插入图片描述
注意:

  • 使用v-slot只能在自定义组件和template模板内使用;

  • 使用slot=“val”时不能在自定义组件内使用,只能在普通标签和template模板中使用,slot-scope相同

小提示:省略写法:v-slot:可省略写为#
即:

  <slotCom>
      <template #a1>
      我是替换a1插槽的内容
    </template>
  </slotCom>

3.作用域插槽

即子组件内的数据被父组件内用到。
子组件:

<template>
<div>
  <slot name="a2" :age="age"></slot>
  </div>
</template>
<script>
export default {
  data(){
    return {
      age:18
    }
  }
}
</script>

父组件:

<template>
<div>
  <slotCom>
    <template #a2="data">
      得到子组件的age是:{{data.age}}
    </template>
  </slotCom>
</div>
</template>

不推荐:

  <slotCom>
    <template slot="a2" slot-scope="data">
      得到子组件的age是:{{data.age}}
    </template>
  </slotCom>

结果:
在这里插入图片描述
提示:使用数据时自定义的名称data后必须要打点加子组件内的对应属性名。

4.动态插槽

即插槽的名字也可以设置一个变量。这里基于es6新增语法
在上面的例子中名字为a2的插槽我们可以设置一个变量:
父组件:

<template>
<div>
  <slotCom>
    <template #[name1+name2]="data">
      得到子组件的age是:{{data.age}}
    </template>
  </slotCom>
  </div>
</template>
<script>
import slotCom from "@/components/slotCom";
export default {
  components:{
    slotCom
  },
  data(){
    return {
      name1:"a",
      name2:"2"
    }
  }
}
</script>

参考

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值