[Vue]組件——插槽:slot(匿名插槽,具名插槽)與slot-scope(作用域插槽)


v-slot 指令自 Vue 2.6.0 起被引入,提供更好的支持 slot 和 slot-scope 特性的 API 替代方案:https://cn.vuejs.org/v2/guide/components-slots.html

1.單個插槽 | 匿名插槽

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>

3.3結果如圖:

 

匿名插槽和具名插槽詳情見:https://cn.vuejs.org/v2/guide/components-slots.html#作用域插槽

作用域插槽詳情見:https://segmentfault.com/a/1190000013277423

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM