Vue学习(5)-插槽slot

插槽就是子组件预留给父组件放置内容的空间,如果没有插槽,那么我们在父组件中使用子组件时,往子组件里添加内容是无效的。
父组件:

<template>
  <div style="text-align: center">
    <todo-item>
      <!-- 子组件标签里的内容将不会显示 -->
      <span>这里是父组件DOM</span>
    </todo-item>
  </div>
</template>

那么有什么办法可以让子组件标签像div一样可以在里面放置内容吗?当然是有的,就是 我们要介绍的插槽slot。

slot

如果我们在子组件中添加插槽,那么放入子组件标签中的内容就会被加载到slot中。
子组件:

<template>
  <div style="text-align: center" class='child'>
    <h3>这是子组件</h3>
    <!-- 像这样添加slot标签即可 -->
   <slot></slot>
  </div>
</template>

这样父组件中添加的内容将会替换掉slot,相当于
子组件:

<div style="text-align: center" class='child'>
    <h3>这是子组件</h3>
    <!-- slot标签会被替换掉 -->
    <span>这里是父组件DOM</span>
</div>

每一个子组件都应该有一个像这样不带名字的插槽,称为单个插槽
同时我们也可以增加一些带有名字的插槽,控制DOM内容的不同位置,带有name属性的插槽称为具名插槽
子组件

<template>
  <div style="text-align: center" class='child'>
    <slot name="top"></slot>
    <h3>这是子组件</h3>
    <slot></slot>
    <hr style="margin-top: 20px">
    <slot name="down"></slot>
  </div>
</template>

父组件中要添加slot属性:

<template>
  <div style="text-align: center">
    <todo-item>
      <span class="father-dom">这里是父组件DOM</span>
      <span slot="down">这是底部</span>
      <span slot="top">这是顶部</span>
    </todo-item>
  </div>
</template>

不管父组件中增加的DOM先后顺序如何,具名插槽总是对应到同名的子组件位置处,剩下的对应到单个插槽处。如果在父组件中给了slot属性,但是子组件中并没有该插槽,那么那个标签将不会显示。

slot-scope

这个属性是给父组件中插入在子组件标签中的DOM使用的,可以获取插槽上的属性值。
父组件

<template>
  <div style="text-align: center">
    <todo-item :message="message">
      <template slot-scope="scope">
        <span>{{scope}}</span><br>
        <span>{{scope.data}}</span>
      </template>
    </todo-item>
  </div>
</template>

子组件:

<template>
  <div style="text-align: center" class='child'>
    <h3>这是子组件</h3>
    <slot :data="message"></slot>
  </div>
</template>

父组件中slot-scope绑定的scope对应的数据就是子组件中slot上的data。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 以下内容是我在学习和研究Vue时,对Vue的特性、重点和注意事项的提取、精练和总结,可以做为Vue特性的字典; 1...
    科研者阅读 14,171评论 3 24
  • 此文基于官方文档,里面部分例子有改动,加上了一些自己的理解 什么是组件? 组件(Component)是 Vue.j...
    陆志均阅读 3,871评论 5 14
  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 5,088评论 0 29
  • 这句话,绝对是一句大实话 2016年,会开始疯狂的变现,你的朋友圈也好,还有你的微信群里都会不断有和耳朵产品推送的...
    刘鹏发烧友阅读 243评论 0 0
  • 初号=42磅 小初=36磅 一号=26磅 小一=24磅 二号=22磅 小二=18磅 三号=16磅 小三=15磅 四...
    WesleyWang阅读 2,749评论 0 1