vue中的slot用法
slot: 插槽。它是元件的一塊html模板,這塊模板顯示不顯示以及怎樣顯示是由父元件來決定的。它用於決定將所攜帶的內容,插入到指定的某個位置,從而使用模板分塊。具有模組化的特性。
slot可以看成是一個空盒子,它顯示與隱藏,用什麼樣的html模板都是由父元件來控制的,它自己本身不能決定,他顯示的位置是由子元件自身來決定的。就自己的理解,我們可以通過slot向子元件的內部指定位置傳遞內容,它可以在子元件中佔好位置,當使用這個元件時,元件標籤裡面的內容就會通過父元件裡的設定進行填充。
匿名slot: 當子元件模板只有一個沒有屬性的slot時,父元件整個內容片斷將插入到slot所在的DOM位置,並且替換slot標籤。它可以放在子元件的任意位置。
<template> <div> <h2>父元件</h2> <myslot> <!-- 在元件中插入p標籤和其內容 --> <i>這裡我插入了內容</i> </myslot> </div> </template> <script> //引入 import slot from "./mySlot.vue"; export default { name: "xxx", data() {return {}; }, components: { myslot } }; </script> <style lang='less'> </style> ----------------------------------- <template> <div> <h2>子元件</h2> <!-- 當父元件中有替代的內容就把slot替換 沒有的話就預設使用slot中的內容替換slot --> <slot> <p>父元件中沒有插入內容時,我就是預設內容</p> </slot> </div> </template>
具名slot: <slot>元素它可以用一個特殊的屬性name來配置如何分發內容,多個slot可以有不同的名字。具名slot將匹配內容片段中有對應slot特性的元素。
在具名slot中,還是可以有一個匿名slot的,它是預設的slot,作為找不到匹配的內容的備用插槽。匿名slot只能它只能是沒有slot屬性的元素的插槽,有slot屬性的元素如果沒有配置slot則會被拋棄。
如果子元件中又有具名slot還有匿名slot,父元件中的所有不帶slot屬性的htlml標籤會被當成一個整體,替換子元件中的slot標籤。
<template>
<div>
<h2>父元件</h2>
<myslot>
<!-- 這個p會替換子元件中name為first的slot標籤 -->
<p slot='fisrt'>匹配第一個slot的內容</p>
<!-- 這個p會替換子元件中name為last的slot標籤 -->
<p slot='last'>匹配最後一個slot內容</p>
<!-- 它會替換子元件中沒有name的slot標籤 -->
<p>其它內容</p>
</myslot>
</div>
</template>
----------------------------------------------------------------
<template>
<div>
<h2>子元件</h2>
<slot name="first">first</slot>
<slot name="last">last</slot>
<slot></slot>
<slot>預設值</slot>
</div>
</template>
或者是可以用v-slot來進行操作。v-slot:插槽名等同於<標籤名 slot="插槽名">,但是它只能用在template上。v-slot可以簡寫成#。
<template>
<div>
<h2>父元件</h2>
<myslot>
<template v-slot:first>
<p>first</p>
</template>
</myslot>
</div>
</template>
---------------------------------
<template>
<div>
<h2>子元件</h2>
<myslot>
<slot name='first'></slot>
</myslot>
</div>
</template>
作用域插槽:它是一種特殊型別的帶資料的插槽。使用一個數據可重用模板替換已渲染好的元素。需要注意是的新版本的寫法。
slot-scope='使用者自己起的名字',這個名字對應的值是子元件(<slot:自定義屬性=‘xxx’</slot>)中的在slot上所有行內屬性組成的物件。
<template>
<div>
<h2>父元件</h2>
<child :list='ary'>
<!-- <h1 slot-scope="aaa">{{aaa}}</h1> -->
<!-- 老版本寫法 -->
<!-- <h1 slot-scope="aaa">{{aaa.www}}</h1> -->
<!-- 新版本寫法 -->
<template #default='aaa'>
<h1>{{aaa.www}}</h1>
</template>
</child>
</div>
</template>
<script>
import childApp from './childApp'
export default{
name: 'App',
data(){
return {
ary:[1,2,3,4,5,6,7]
}
},
components:{
"child":childApp
}
}
</script>
<style lang='less'>
</style>
<template>
<div>
<h2>子元件</h2>
<ul>
<li v-for="i in list" :key="i">
<slot :www="i"></slot>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "childApp",
//用props接收父元件傳過來的值
props: ["list"],
data() {
return {};
},
components: {}
};
</script>
<style lang='less'>
</style>