自建服務(wù)器網(wǎng)站備案營(yíng)銷廣告文案
不僅父組件可以通過(guò)插槽方式訪問(wèn)并控制子組件傳入的數(shù)據(jù),而且可以控制傳入父組件時(shí)插槽的名稱,從而使不同的插槽根據(jù)名稱的不同,使用場(chǎng)景也不同,例如在一個(gè)小區(qū)詳細(xì)頁(yè)中,可以根據(jù)小區(qū)類型,調(diào)用不同名稱的詳細(xì)頁(yè)插槽,這種插槽就是動(dòng)態(tài)插槽。
接下來(lái),結(jié)合一個(gè)完整的實(shí)例,來(lái)演示使用動(dòng)態(tài)插槽,實(shí)現(xiàn)一個(gè)tab選項(xiàng)卡的功能。
實(shí)例7-6 動(dòng)態(tài)插槽應(yīng)用
1. 功能描述
在一個(gè)父組件中,添加一個(gè)子組件,子組件中是各種不同名稱的slot插槽,當(dāng)點(diǎn)擊父組件選項(xiàng)卡標(biāo)題時(shí),就選中了一個(gè)插槽的名稱,則在內(nèi)容中,顯示對(duì)應(yīng)名稱的插槽。
2. 實(shí)現(xiàn)代碼
在項(xiàng)目的components 文件夾中,添加一個(gè)名為“Parent”的.vue文件,該文件的保存路徑是“components/ch7/part6/”,在文件中加入如清單7-13所示代碼。
代碼清單7-13 Parent.vue代碼
<template><ul><li :key="index" v-for="item,index in tabs" :class="{ 'focus': index == sIdx }" @click="clk(item.sName, index)">{{ item.title }}</li></ul><child><template #[sName]><div class="content">{{ tabs[sIdx].content }}</div></template></child>
</template>
<script>
import Child from "./Child.vue"
export default {data() {return {tabs: [{sName: "s1",title: "新聞",content: "新聞內(nèi)容很豐富"}, {sName: "s2",title: "熱點(diǎn)",content: "熱點(diǎn)事件也不少"}, {sName: "s3",title: "圖片",content: "圖片資訊更精彩"}],sName: "s1",sIdx: 0}},methods: {clk(n, i) {this.sName = n;this.sIdx = i}},components: {Child}
}
</script>
<style scoped>
ul {padding: 0;margin: 0;list-style: none;display: flex;justify-content: space-around;width: 300px;border: solid 1px #ccc;
}ul>li {padding: 8px;cursor: pointer;width: 84px;text-align: center;
}ul .focus {background-color: #ccc;font-weight: 700;
}.content {width: 260px;border: solid 1px #ccc;border-top: none;padding: 20px;
}
</style>
在父組件中,導(dǎo)入子組件 Child.vue文件,它的功能是為父組件提供各類名稱的模板,父組件根據(jù)slot插槽的name屬性值就可以動(dòng)態(tài)加載,它的代碼如清單7-14所示。
代碼清單7-14 Child.vue代碼
<template><div v-for="(item, index) in names" :key="index"><slot :name="item"></slot></div>
</template>
<script>
export default {data() {return {names: ["s1","s2","s3"]}}
}
</script>
3. 頁(yè)面效果
保存代碼后,頁(yè)面在Chrome瀏覽器下執(zhí)行的頁(yè)面效果如圖7-7所示。
4. 源碼分析
在本實(shí)例的子組件Child源碼中,向父組件提供了多個(gè)不同name的slot插槽,供父組件中template元素使用,使用的方法是在模板中添加#符號(hào),符號(hào)后面是slot插槽的名稱,由于該名稱是一個(gè)動(dòng)態(tài)的變量sName,因此需要使用[]方括號(hào)進(jìn)行包裹。
在父組件中,當(dāng)用戶點(diǎn)擊某個(gè)導(dǎo)航欄選項(xiàng)時(shí),在單擊事件中獲取到對(duì)應(yīng)的slot插槽名稱和索引號(hào),則將前者傳給變量sName,使父組件中template元素替換sName名稱的插槽;后者傳給變量sIdx,通過(guò)sIdx值獲取到對(duì)應(yīng)的數(shù)組內(nèi)容,并顯示在插槽中。