Vue插槽詳解
阿新 • • 發佈:2020-12-20
先看如下程式碼:
//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>
插槽基本用法就是這樣,更多的應用還需要自己在實際專案中體會。