slot插槽

插槽语法是Vue实现的内容分发API,用于复合组件开发。该技术在通用组件库开发中有大量应用。

插槽有三种:匿名插槽、具名插槽和作用域插槽;

  1.   匿名插槽 
//子组件children.vue
<div>
  <slot></slot>
</div>
  //slot 里面没有name属性,为匿名插槽
 
  //父组件parent.vue
<children>
  <template slot="content">
    父组件引用子组件
  </template>
<children>
//<children>标签里面的内容全部默认分发到children.vue的slot里面
 

  2.  具名插槽

//子组件children.vue
<div>
  <slot name="content"></slot>
</div>
  //slot 里面name属性作用标记
 
  //父组件parent.vue
<children>
  <template slot="content">
    父组件引用子组件
  </template>
<children>
//<children>标签里面的内容分发到children.vue里对应的name属性slot位置
//这是具名插槽的使用方法
//vue 2.6.0起不再使用slot=""方法,而使用v-slot方式, 注意:v-slot只能添加在<template>上
<children>
  //匿名插槽用default做参数
  <template v-slot:default>
    父组件引用子组件
  </template>
 
  //具名插槽用插槽名做参数
  <template v-slot:content>
    父组件引用子组件
  </template>
</children>
 
 

 

  3.作用域插槽

分发内容要用到子组件中的数据时,可以使用作用域插槽

//子组件 children.vue
<div>
  <slot :foo="foo"><slot>
</div>

//父组件 parent.vue
<children>
    //把v-slot的值指定为作用域上下文对象
  <template v-slot:default="slotProps">
    来自子组件数据: {{ slotProps.foo }}
  </template>  
<children>

 

posted @ 2019-10-09 00:57  迷眼世尘  阅读(240)  评论(0)    收藏  举报