By Leafhtml
在學習的過程當中遇到了Vue的slot元素,開始不知道也不瞭解它的用途、用法,即然遇到了不懂的知識點我就學習一下。vue
官網上對slot的理解是:bash
「Vue實現了一套內容分發的API,這套API基於當前的Web Components規範草案,將slot元素做爲承載分發內容的接口」。學習
在參考了不少資料以後,如下總結一下我對slot的理解: slot的意思是插槽,Vue使用slot的做用是作內容分發。所謂的內容分發其實就是將父組件的內容放到子組件指定的位置叫作內容分發。 在咱們的電腦主板上也有各類各樣的插槽,有插CPU的,有插顯卡的,有插內存的,有插硬盤的。咱們能夠理解slot爲要佔出當前的位置,方便咱們插入內容。或者能夠這樣理解:要去吃飯了,兒子先去佔座,而後等他爸爸來了再一塊兒吃。 Vue的插槽分爲匿名插槽(單個插槽/默認插槽)、具名插槽、做用域插槽(帶數據的插槽)。 ####匿名插槽(單個插槽/默認插槽)flex
<!-- 父組件-->
<template>
<div class="father">
<h3>這裏是父組件</h3>
<chlid>
<div class="tmp1">
<span>Leaf 1</span>
<span>Leaf 2</span>
<span>Leaf 3</span>
<span>Leaf 4</span>
<span>Leaf 5</span>
</div>
</child>
</div>
</template>
<script>
import Child from '@/components/child'
export default {
components:{
child:child
}
}
</script>
<style>
.tmp1 span{
width: 50px;
height: 50px;
border: 1px solid black;
}
</style>
複製代碼
<!--子組件-->
<template>
<div>
<slot></slot>
<h2>child子組件部分</h2>
</div>
</template>
複製代碼
最終呈現效果: ui
<template>
<div>
<h2>child子組件部分</h2>
<slot></slot>
</div>
</template>
複製代碼
改變slot位置後的最終呈現效果以下: spa
只有在父組件的child下寫了html模板,才能在子組件指定的位置放父組件的內容。插槽最後顯示不顯示是看父組件有沒有在child下寫模板,像下面同樣:3d
<child>
html模板
</child>
複製代碼
####具名插槽code
<!--父組件-->
<template>
<div class="father">
<h3>這裏是父組件</h3>
<chlid>
<div class="tmp1" slot="up">
<span>Leaf 1</span>
<span>Leaf 2</span>
<span>Leaf 3</span>
<span>Leaf 4</span>
<span>Leaf 5</span>
</div>
<div class="tmp1" slot="down">
<span>Leaf 6</span>
<span>Leaf 7</span>
<span>Leaf 8</span>
<span>Leaf 9</span>
<span>Leaf 10</span>
</div>
</child>
</div>
</template>
<script>
import Child from '@/components/child'
export default {
components:{
child:child
}
}
</script>
<style>
.tmp1 span{
width: 50px;
height: 50px;
border: 1px solid black;
}
</style>
複製代碼
<!--子組件-->
<template>
<div>
<slot name="up"></slot>
<h2>chlid子組件部分</h2>
<slot name="down"></slot>
</div>
</template>
複製代碼
最終呈現效果: component
<!--父組件-->
<template>
<div class="father">
<h3>這裏是父組件</h3>
<chlid>
<!-- 第一次使用:用flex展現數據 -->
<template slot-scope="user">
<div class="tmp1">
<span v-for="(item,index) in user.data" :key="index">{{item}}</span>
</div>
</template>
<!-- 第二次使用:用列表展現數據 -->
<template slot-scope="user">
<ul>
<li v-for="(item,index) in user.data" :key="index">{{item}}</li>
</ul>
</template>
<!-- 第三次使用:直接顯示 -->
<template slot-scope="user">
{{user.data}}
</template>
</child>
</div>
</template>
<script>
import Child from '@/components/child'
export default {
components:{
child:child
}
}
</script>
<style>
.tmp1 span{
width: 50px;
height: 50px;
border: 1px solid black;
}
</style>
複製代碼
<!--子組件-->
<template>
<div>
<h2>chlid子組件部分</h2>
<slot :data="data"></slot>
</div>
</template>
<script>
export default {
props: ["message"],
data () {
return {
data: [''小莊','CC','小張','小林','Leaf','Bob'] } } } </script> 複製代碼
經過3種方式顯示數據的最終呈現效果分別以下: 一、flex顯示
這裏咱們所看到的數據「'小莊','CC','小張','小林','Leaf','Bob'」都是子組件data提供的數據,父組件若是要使用這些數據必需要經過template模板結合slot-scope來呈現。
這裏只是將本身學到的知識作一個總結,方便本身記憶和查閱,可能會有錯,望大神指點!