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

一、插槽

当子组件的有一部分内容是根据父组件传过来的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>

 

posted @ 2020-08-16 16:33  海绵宝宝y  阅读(671)  评论(0编辑  收藏  举报