1. 程式人生 > 實用技巧 >插槽、具名插槽、作用域插槽

插槽、具名插槽、作用域插槽

一、插槽

當子元件的有一部分內容是根據父元件傳過來的dom顯示的時候,可以使用插槽

通過插槽,父元件向子元件優雅的傳遞dom結構,同時子元件使用插槽的內容,通過<slot></slot>

body>
    <div id="root">
      <child>
        <p>well</p>
      </child>
    </div>
      
    <script>
      Vue.component('child',{
      
        template:`
<div> <p>hello</p> <slot></slot> </div>` }) var vm = new Vue({ el:"#root" }) </script> </body>

二、具名插槽

<body>
    <div id="root">
     <body-content>
       <div class="header" slot="header"
>header</div> <div class="footer" slot="footer">footer</div> </body-content> </div> <script> Vue.component('body-content',{ template:`<div> <slot name="header"></slot> <div class="content">content</div> <slot name="footer"
></slot> </div>` }) var vm = new Vue({ el:"#root" }) </script> </body>

三、作用域插槽

作用域插槽:每一項顯示什麼就不是由子元件決定了,而是父元件調子元件的時候給子元件重遞對應的模板,

作用域插槽必須是template開頭和結尾的一個內容,同時插槽要用v-slot宣告要從子元件接收的資料放到哪裡,同時要告訴子元件一個模板資訊,你接收到的內容應該怎麼展示

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>插槽、具名插槽、作用域插槽</title>
  <script src="vue.js"></script>
</head>
<body>
    <div id="root">
     <child>
       <template v-slot="props">   // v-slot宣告要從子元件接收的資料放到props裡
         <li>{{props.item}}-hello</li>   // 告訴子元件一個模板資訊,接收到的內容應通過li標籤的形式展示
       </template>>
     </child>
    </div>
    
    <script>
      Vue.component('child',{
        data:function(){
          return{
            list:[1,2,3,4]
          }

        },
        template:`<div>
                    <ul>
                      <slot 
                        v-for="item in list"
                        :item=item   //子元件向父元件傳遞內容
                      >
                        {{item}}
                      </slot>
                    </ul>
                  </div>`
      })
      var vm = new Vue({
        el:"#root"
      })
    </script>
</body>
</html>