12.在vue中插槽(slot)

weixin_34249678發表於2018-07-07

父元件怎樣優雅的向子元件傳遞dom結構

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>元件的插槽(slot)</title>
    <!--引入/vue.js-->
    <script src="./vue.js"> </script>
</head>
<body>
   <div id="root">
       <!-- <child content="<p>Dell</p>"> 
       </child> -->
       <child >
            <p>Dell</p>
       </child>
   
   </div>

   <script>  
       Vue.component('child',{
           props:['content'],
           template:'<div> <p>Dell</p> <slot>預設內容</slot> </div>'
        })
       var app = new Vue({
           el:'#root'
       })

   </script>

</body>

</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>元件的插槽(slot)</title>
    <!--引入/vue.js-->
    <script src="./vue.js"> </script>
</head>
<body>
   <div id="root">
       <!-- <child content="<p>Dell</p>"> 
       </child> -->
       <body-content >
            <div class="header" slot="header">header</div>
            <div class="footer" slot='footer'>footer</div>
       </body-content>
   
   </div>

   <script>  
       Vue.component('body-content',{
           props:['content'],
           template:'<div> <slot name="header"> </slot> Dell <slot name="footer"> </slot> </div>'
        })
      
 
       var app = new Vue({
           el:'#root'
       })

   </script>

</body>

</html>

3.作用域插槽

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>元件的插槽(slot)</title>
    <!--引入/vue.js-->
    <script src="./vue.js"> </script>
</head>
<body>
   <div id="root">
       <!-- <child content="<p>Dell</p>"> 
       </child> -->
       <body-content >
          <!-- 作用域插槽必須使用template標籤,資料放在props,應該怎樣展示 -->
          <template slot-scope="props">
              <li>{{props.item}}-hello</li>
          </template>
        
       </body-content>
   
   </div>

   <script>  

       Vue.component('body-content',{
           data:function(){
               return{
                   list:[1,2,3,4]
               }
           },
           template:'<div> <ul> <slot v-for="item of list":item=item> {{item}} </slot"> </ul> </div>'
        })
 
       var app = new Vue({
           el:'#root'
       })

   </script>

</body>

</html>

相關文章