vue组件开发之组件插槽

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/poppy995/article/details/98342749

组件插槽

作用
父组件向子组件传递内容


基本用法

  1. 插槽位置
  	Vue.component('alert-box',{
   	 template:`
    	  <div class="demo-alert-box">
     	   <strong>Error!</strong>
     	   <slot></slot>//这就是插槽
   	   </div>
    `
  })
  1. 插槽内容
    Something bad happened.
    Something bad happened.这个内容就会显示在插槽中,
    如果在默认内容没有传递数据,那么就显示默认内容,传递了就显示传递的内容
  2. 具名插槽定义 就是有名字的插槽
    定义
      <slot name="header"></slot>
    
    内容
       <h1 solt="header">内容</h1>
    
    没有名称的话就匹配到没有name属性的插槽中
    还可以使用template标签进行使用

    template只是暂时包裹要显示的内容,可以包裹多个,它不会显示在页面中
    使用两个相同具有相同名称的slot可以显示在页面中 name这个有什么用???
  3. 作用域插槽
    应用场景:父组件对子组件的内容进行加工处理
    1. 插槽定义
             <ul>
               <li v-for="item in list" v-bind:key="item.id">
                 <slot v-bind:item="item">
                   {{item.name}}
                 </slot>
               </li>
             </ul>
      
      v-bind:item绑定的数据是要给父组件用的
    2. 插槽内容
      v-bind:list="list"是为了让子组件可以使用父组件中的值 子组件中有props[‘list’]
      <fruit-list v-bind:list="list">
        <template slot-scope="soltProps">
          <strong v-if="slotProps.item.current">
          {{slotProps.item.text}}
          </strong>
        </template>
      </fruit-list>
      
      slot-scope可以得到子组件中绑定属性的那个数据
      //插槽(匿名插槽) 只需要传递一块内容
      //具名

作用域插槽

  1. 还是插槽
  2. 插槽中要使用变量数据
  3. 变量数据来自于子组件内部
  4. <slot a=100></slot>
  5. <template slot-scope="scope">{{scope.a}}</template>

猜你喜欢

转载自blog.csdn.net/poppy995/article/details/98342749
今日推荐