vue slot插槽的使用方法

 官方文檔其實已經講得很詳細,我根據文檔,把官方的小案例實現了一下,這樣更直觀html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://unpkg.com/vue@2.3.3/dist/vue.js"></script>
</head>

<body>
  <div id="app">
    <div>
      <!-- 單slot -->
      <v-one>
        <!-- 這裏的全部內容會替換掉slot -->
        <p>初始化段落一</p>
        <p>初始化段落二</p>
      </v-one>
      <!-- 渲染結果 -->
      <!-- <div>
        <h1>組件標題</h1>
        <p>初始化段落一</p>
        <p>初始化段落二</p>
        <p>組件段落內容</p>
        <p>I am one</p>
      </div> -->


      <!-- 具名slot -->
      <v-two>
        <p slot="nav">我是導航</p>
        <p slot="main">我是內容</p>
        <p slot="footer">我是底部</p>
      </v-two>
      <!-- 渲染結果 -->
      <!-- <div>
        <nav>
          <p>我是導航</p>
        </nav>
        <main>
          <p>我是內容</p>
        </main>
        <footer>
          <p>我是底部</p>
        </footer>
      </div> -->


      <!-- 做用域插槽 -->
      <v-three>
      <!-- 父組件默認沒法使用子組件數據 -->
          <template scope="props">
              <p>{{props.text}}</p>
          </template>
      </v-three>

      <!-- 渲染結果 -->
      <!-- <div><p>I am three</p></div> -->
    </div>
  </div>


  <template id="one">
    <div>
      <h1>組件標題</h1>
      <slot></slot>
      <p>組件段落內容</p>
      <p>{{one}}</p>
    </div>
  </template>


  <!-- 具名slot -->
  <template id="two">
    <div>
      <nav>
        <slot name="nav"></slot>
      </nav>
      <main>
        <slot name="main"></slot>
      </main>
      <footer>
        <slot name="footer"></slot>
      </footer>
    </div>
  </template>

<!-- 做用域插槽 -->
  <template id="three">
    <div>
        <!-- 把數據傳遞給slot,這樣父組件也能夠訪問three這個組件的數據 -->
      <slot :text="three"></slot>
    </div>
  </template>
  <script>
  new Vue({
    el: '#app',
    components: {
      'v-one': {
        template: '#one',
        data() {
          return {
            'one': 'I am one'
          }
        }
      },
      'v-two': {
        template: '#two',
        data() {
          return {
            'two': 'I am two'
          }
        }
      },
      'v-three': {
        template: '#three',
        data() {
          return {
            'three': 'I am three'
          }
        }
      }
    }
  });
  </script>
</body>

</html>

單個slot使用最簡單,也是最經常使用的,當咱們定義了一個子組件,父組件在使用的這個組件的時候,想在內部自定義一些初始化數據,這時候就能夠用slot實現。vue

具名slot只是給slot加了name屬性,在使用的時候能夠引入多個。瀏覽器

做用域slot就比較強大了,咱們知道子組件的數據,在父組件中是沒法使用的,可是經過官方提供的擴展,能夠輕鬆實現這一點。app

渲染後效果圖,能夠直接複製代碼本身在瀏覽器運行查看效果spa

相關文章
相關標籤/搜索