1. 程式人生 > >vue2.0——slot 插槽

vue2.0——slot 插槽

單個插槽
<template>
    <div id="example">
        <h1>我是父元件的標題</h1>
        <app-layout>


          <p>主要內容的一個段落。</p>
          <p>另一個主要段落。</p>

          <p slot="footer">這裡有一些聯絡資訊</p>
          <h1 slot="header">這裡可能是一個頁面標題</h1
>
</app-layout> </div> </template> <script> export default{ components:{ 'app-layout': { template: ` <div> <h2>我是子元件的標題</h2> <slot> 只有在沒有要分發的內容時才會顯示。 </slot
>
</div> `, } } }
</script>

渲染結果

<div>
  <h1>我是父元件的標題</h1>
  <div>
    <h2>我是子元件的標題</h2>
    <p>這是一些初始內容</p>
    <p>這是更多的初始內容</p>
  </div>
</div>
具名插槽
<template
>
<div id="example"> <h1>我是父元件的標題</h1> <app-layout> <h1 slot="header">這裡可能是一個頁面標題</h1> <p>主要內容的一個段落。</p> <p>另一個主要段落。</p> <p slot="footer">這裡有一些聯絡資訊</p> </app-layout> </div> </template> <script> export default{ components:{ 'app-layout': { template: ` <div class="container"> <header> <slot name="header"></slot> </header> <main> <slot></slot> </main> <footer> <slot name="footer"></slot> </footer> </div> `, } } } </script>

渲染結果為:

<div class="container">
  <header>
    <h1>這裡可能是一個頁面標題</h1>
  </header>
  <main>
    <p>主要內容的一個段落。</p>
    <p>另一個主要段落。</p>
  </main>
  <footer>
    <p>這裡有一些聯絡資訊</p>
  </footer>
</div>
作用域插槽
<template>
    <div id="example">
        <div class="parent">
            <child>
                <template slot-scope="props">
                    <span>hello from parent</span><br/>
                    <span>{{ props.text }}</span>
                </template>
            </child>
        </div>
    </div>
</template>
<script>
    export default{
        components:{
            'child': {
                template: `
                    <div class="child">
                      <slot text="hello from child"></slot>
                    </div>
                `,
            }
        }
    }
</script>

渲染結果為:

<div class="parent">
  <div class="child">
    <span>hello from parent</span>
    <span>hello from child</span>
  </div>
</div>