vue 初识-插槽

1.单个插槽、匿名插槽

在子组件中,可以这样写

<a
  v-bind:href="url"
  class="nav-link"
>
  <slot></slot>
</a>

然后在父组件中可以像如下使用子组件:

<navigation-link url="/profile">
  Your Profile
</navigation-link>

当组件被渲染时,slot 会被替换为 Your Profile

<a
  v-bind:href="url"
  class="nav-link"
>
  Your Profile
</a>
  1. 具名插槽

需要多个插槽时,我们可以利用 slot 的一个特殊特性,name 来定义具名插槽,在向具名插槽提供内容的时候,我们可以在一个 <template> 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称,(v-slot 可以缩写为 # ) :

子组件中这样定义:

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

父组件中使用子组件,节点上使用 slot 特性:

<base-layout>
  <h1 v-slot:header>Here might be a page title</h1>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <p v-slot:footer>Here's some contact info</p>
</base-layout>

也可以在外层套用一个 templete 节点,在节点上使用 slot 属性。

渲染出来的 HTML 都将会是:

<div class="container">
  <header>
    <h1>Here might be a page title</h1>
  </header>
  <main>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </main>
  <footer>
    <p>Here's some contact info</p>
  </footer>
</div>
  1. 作用域插槽---带数据的插槽

单个插槽和具名插槽都不绑定数据,所以父组件既要提供样式又要提供数据,作用域插槽是子组件提供数据,父组件只提供样式

子组件中:

<template>
  <div class="child">

    <h3>这里是子组件</h3>
    // 作用域插槽
    <slot  :data="data"></slot>
  </div>
</template>

 export default {
    data: function(){
      return {
        data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
      }
    }
}

父组件中:

<template>
  <div class="father">
    <h3>这里是父组件</h3>
    <!--第一次使用:用flex展示数据-->
    <child>
      <template slot-scope="user">
        <div class="tmpl">
          <span v-for="item in user.data">{{item}}</span>
        </div>
      </template>

    </child>

    <!--第二次使用:用列表展示数据-->
    <child>
      <template slot-scope="user">
        <ul>
          <li v-for="item in user.data">{{item}}</li>
        </ul>
      </template>

    </child>

    <!--第三次使用:直接显示数据-->
    <child>
      <template slot-scope="user">
       {{user.data}}
      </template>

    </child>

    <!--第四次使用:不使用其提供的数据, 作用域插槽退变成匿名插槽-->
    <child>
      我就是模板
    </child>
  </div>
</template>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 【2019-3-4更新】Vue 2.6+修改了部分语法,对插槽的使用有了较多的更新。在本文中笔者在相应位置给出了更...
    果汁凉茶丶阅读 10,287评论 2 36
  • 什么是组件? 组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装...
    youins阅读 9,522评论 0 13
  • 本章内容:表单 与 v-model、组件、自定义指令 六、表单 与 v-model 6.1、基本用法 Vue.js...
    了凡和纤风阅读 929评论 1 2
  • 深入理解vue中的slot与slot-scope 写在前面 vue中关于插槽的文档说明很短,语言又写的很凝练,再加...
    SentMes阅读 42,597评论 14 55
  • 此文基于官方文档,里面部分例子有改动,加上了一些自己的理解 什么是组件? 组件(Component)是 Vue.j...
    陆志均阅读 3,846评论 5 14