slot 插槽

slot 插槽

一、使用背景

一般在封装组件的时候,我们会用到插槽

二、插槽类型

1、默认插槽

<div class="container">
  <son>
    <h1>你好啊</h1>
  </son>
</div>
<div class="son">
  <slot />
</div>
  • 在没有使用插槽的情况下,若在组件标签里面写内容是不会显示的,因为它不知道把这东西具体放在组件的哪个位置。你需要在组件的模板中写一个<slot/>标签,相当于给你写的东西预留了一个位置,我们管这种写法叫做默认插槽。它是把在组件标签里面写的东西视为一个整体,都放入<slot/>中,若你写了多个,则还会再放一遍

2、具名插槽(具有名字的插槽)

<div class="container">
  <son>
    <template v-slot:test>
      <h1>你好啊</h1>
    </template>
  </son>
</div>
<div class="son">
  <slot name="test"/>
</div>

3、作用域插槽

<div class="container">
  <son>
    <template v-slot="scope">
<!--        scope 名字可以任意-->
      <h1>{{scope.test}}</h1>
      <h1>{{scope.test2}}</h1>
    </template>
  </son>
</div>
<template>
  <div class="son">
    <slot :test="test" :test2="test2"/>
  </div>
</template>

<script>
export default {
  name: 'son',
  data() {
    return {
      test: '我是Jackson',
      test2: '我是tom'
    //  就相当于是反向的props
    }
  }
}
</script>

其实插槽也算是组件间通信的一种方式,因为它也算是把父组件里的东西放到子组件里的插槽里面了嘛

巧记:slot 标签就是一个占位符

相关链接:

插槽 — Vue.js (vuejs.org)

rfcs/0001-new-slot-syntax.md at master · vuejs/rfcs (github.com)

https://www.bilibili.com/video/BV1Zy4y1K7SH?p=104&share_source=copy_web

posted @ 2022-06-09 15:03  朱在春  阅读(57)  评论(0编辑  收藏  举报