组件--插槽:匿名插槽 具名插槽

单个插槽|匿名插槽

1.1  <navigation-link> 子组件定义为:

<a v-bind:href="url" class="nav-link">
  <slot></slot>
</a>
1.2 父组件向一下这样使用<navigation-link>子组件
<navigation-link url="/profile">
  Your Profile
</navigation-link>

1.3渲染出来的 HTML 将会是:

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

2.具名插槽

需要多个插槽时,可以利用<slot> 元素的一个特殊的特性:name来定义具名插槽

 

2.1<base-layout>子组件模板定义:

复制代码
<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>
复制代码

 

2.2.1父组件使用子组件<base-layout>,节点上使用slot特性:

复制代码
<base-layout>
  <h1 slot="header">Here might be a page title</h1>

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

  <p slot="footer">Here's some contact info</p>
</base-layout>
复制代码

 

2.2.2也可在内容外层套一个节点,并在外层节点上使用slot特性:

复制代码
<base-layout>
  <template slot="header">
    <h1>Here might be a page title</h1>
  </template>

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

  <template slot="footer">
    <p>Here's some contact info</p>
  </template>
</base-layout>
复制代码

 

2.3渲染出来的 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>
复制代码

 

3.作用域插槽——带数据的插槽

单个插槽和具名插槽中插槽上不绑定数据,所以父组件提供的模板既要包括样式又要包括数据,而作用域插槽是子组件提供数据,父组件只需要提供一套样式

3.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']
      }
    }
}
复制代码

 

3.2父组件:

复制代码
<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>

 

转载于:https://www.cnblogs.com/yangjingyang/p/11390925.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值