以下內(nèi)容均是2.0版本vue中插槽的用法,3.0版本中寫法不完全一樣,有增加一些內(nèi)容,并且2.0版本中的很多屬性已被棄用!slot-scope scope方法已被棄用,作用域插槽3.0寫法是不一致的。
首先我們要搞明白插槽是干什么用的,就是當(dāng)你使用編寫組件時(shí),組件里面的內(nèi)容不完全相同時(shí),如果瘋狂使用v-show或者v-if來控制不同的組件展示不同的內(nèi)容會有些許的麻煩,插槽就相當(dāng)于是在父組件頁面中的子組件標(biāo)簽里面編寫一段代碼,然后這段代碼會被插入到子組件里面,但是子組件本身是有dom元素的,所以插入的時(shí)候需要根據(jù)slot標(biāo)簽的位置來決定插入的位置,又或者是根據(jù)slot的名稱來確定。
插槽分為三種:
1.默認(rèn)插槽
個(gè)人理解,就相當(dāng)于是組件中無法公用的部分需要通過插槽的方式來進(jìn)行插入到子組件里面,代碼如下
父組件代碼:
<template>
<div class="list">
<category title="類目一">
<h3>類目一的自定義內(nèi)容</h3>
</category>
<category title="類目二">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</category>
<category title="類目三">
<div>類目三的自定義內(nèi)容</div>
</category>
</div>
</template>
<script>
import category from "./components/category.vue";
export default {
name: "App",
components: {
category,
},
};
</script>
子組件代碼:
<template>
<div class="category">
<h3>{{title}}</h3>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'category',
props:{
title:null,
}
}
</script>
2.具名插槽
就比如我上方的代碼想要添加兩個(gè)插槽要怎么做?就相當(dāng)于是需要給插槽加一個(gè)名字,子頁面相對應(yīng)的部分改成template外加 v-slot:名字這種方式,slot=" 名字"這種在vue3.0版本中已棄用!
父組件代碼:
<template>
<div class="list">
<category title="類目一">
<template v-slot:center>
<h3>類目一插槽中間</h3>
</template>
<template v-slot:footer>
<h4>類目一插槽底部</h4>
</template>
</category>
<category title="類目二">
<template v-slot:center>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</template>
<template v-slot:footer>
<h4>類目二插槽底部</h4>
</template>
</category>
<category title="類目三">
<template v-slot:center>
<h3>類目三插槽中間</h3>
</template>
<template v-slot:footer>
<h4>類目三插槽底部</h4>
</template>
</category>
</div>
</template>
<script>
子組件代碼:
<template>
<div class="category">
<h3>{{title}}</h3>
<slot name="center"></slot>
<slot name="footer"></slot>
</div>
</template>
<script>
export default {
name: 'category',
props:{
title:null,
}
}
</script>
3.作用域插槽
就相當(dāng)于在數(shù)據(jù)在子組件里面,但是不公用的代碼結(jié)構(gòu)在父組件中,父組件需要拿到子組件的數(shù)據(jù),這個(gè)時(shí)候就需要用到作用域插槽。
父組件代碼:
<template>
<div class="list">
<category title="類目一">
<template slot-scope="{ listData }">
<!-- {{categoryData}} -->
<ul>
<li v-for="(item, index) in listData" :key="index">{{ item }}</li>
</ul>
</template>
</category>
<category title="類目二">
<template slot-scope="{ listData }"> //結(jié)構(gòu)賦值,這里拿到的數(shù)據(jù)是一個(gè)對象
<ol>
<li v-for="(item, index) in listData" :key="index">{{ item }}</li>
</ol>
</template>
</category>
</div>
</template>
<script>
import category from "./components/category.vue";
export default {
name: "App",
components: {
category,
},
};
</script>
子組件代碼:
<template>
<div class="category">
<h3>{{ title }}</h3>
<slot :listData="listData"></slot>
</div>
</template>
<script>
export default {
name: "category",
props: {
title: null,
},
data() {
return {
listData: ["游戲", "電影", "綜藝", "紀(jì)錄片"],
};
},
};
</script>