Vue插槽详解

先看如下代码:

//app.vue
<template>
    <div>
      <Child>
   <span>小红</span>
</Child> </div> </template>
import Child from './child.vue'
<script>
components:{
Child
}
</script>
//child.vue
<template>
    <div>
      <span>小明<span>   
    </div>
</template>

渲染的界面只有小明,小红没渲染出来。

这个时候我们给child.vue一个<slot></slot>插槽

//child.vue
<template>
    <div>
      <span>小明</span> 
      <slot></slot>
    </div>
</template>

小明和小红都渲染出来了,这就是插槽的作用

插槽是Vue实现的一套内容分发API,<slot>标签作为内容分发的出口,没有插槽的情况下,在组件内写内容是不会起作用的。

插槽目前分为三类:

匿名插槽(默认插槽)

  如上:直接给一个slot默认的标签来分发内容,就是默认插槽

具名插槽:

  通过name属性给插槽起一个名字,在填充内容时通过v-slot指令绑定插槽名字来匹配分发数据

//app.vue
<template>
    <div>
      <Child>
<template v-slot:m>
很帅
</template>    <span>小红</span>
<template v-slot:h>
很美
</template> </Child> </div> </template> import Child from './child.vue' <script> components:{ Child } </script>
//child.vue
<template>
    <div>
      <span>小明</span> 
      <slot name="m"></slot>
    <slot></slot>
<slot name="h"></slot>
</div> </template>

作用域插槽:

  可用于组件之间数据通信

//app.vue
<template>
    <div>
      <Child>
       <template v-slot:default="slotProps">
     //default是匿名插槽的默认名字
     //slotProps是定义的一个接收数据的变量,{say:'hello'} {{slotProps.say}} //hello </template> </Child> </div> </template> import Child from './child.vue' <script> components:{ Child } </script>
//child.vue
<template>
    <div>
    <slot say="hello"></slot>
    </div>
</template>

插槽基本用法就是这样,更多的应用还需要自己在实际项目中体会。

 
原文地址:https://www.cnblogs.com/cqweb/p/14163302.html