Vue默認插槽,具名插槽,作用域插槽定義及使用方法
應用場景:
插槽的作用是在子組件中某個位置插入父組件的自定義html
結(jié)構(gòu)和data
數(shù)據(jù)
一、三種插槽的定義
插槽分為三種:
- 默認插槽 具名插槽 作用域插槽
1.默認插槽
【定義:默認插槽是將父組件的結(jié)構(gòu)和數(shù)據(jù)插入子組件中,默認插槽只有一個插入位置,要插入的html結(jié)構(gòu)和data數(shù)據(jù)必須在父組件中,不過css可以在子組件中】
【簡述:將父組件的自定義html和data插入子組件的對應位置】
【特點:父組件決定結(jié)構(gòu)和數(shù)據(jù)】
2.具名插槽
【定義:具名插槽和默認插槽類似,只是默認插槽只有一個插入位置,具名插槽可以有多個插入位置】
【簡述:將多個父組件的自定義html和data插入子組件的多個位置】
【特點:父組件決定結(jié)構(gòu)和數(shù)據(jù)】
3.作用域插槽
【定義:作用域插槽的data數(shù)據(jù)固定寫在子組件中,數(shù)據(jù)的html結(jié)構(gòu)根據(jù)父組件傳入的html結(jié)構(gòu)來決定】
【簡述:根據(jù)父組件中不同的html結(jié)構(gòu)解析data中的數(shù)據(jù)】
【特點:子組件決定數(shù)據(jù),父組件決定結(jié)構(gòu)】
二、使用方法
1.默認插槽
父組件:
<template> ?? ?<Child> <!-- Child為子組件標簽 --> ?? ??? ?<!-- 插槽內(nèi)容 --> ?? ??? ?<template>要插入的html內(nèi)容</template> ?? ?</Child> </template>
子組件:
<template> ?? ?<div> ?? ??? ?<!-- 插槽位置 --> ?? ??? ?<slot>插槽未被調(diào)用時會顯示此內(nèi)容</slot> ?? ?</div> </template>
2.具名插槽
父組件:
<template> ?? ?<Child> <!-- Child為子組件標簽 --> ?? ??? ?<!-- 插槽內(nèi)容 --> ?? ??? ?<template slot="header">要插入的html內(nèi)容1</template> ?? ??? ?<template slot="center">要插入的html內(nèi)容2</template> ?? ??? ?<template slot="footer">要插入的html內(nèi)容3</template> ?? ?</Child> </template>
子組件:
<template> ?? ?<div> ?? ??? ?<!-- 插槽位置 --> ?? ??? ?<slot name="header">插槽未被調(diào)用時會顯示此內(nèi)容</slot> ?? ??? ?<slot name="center">插槽未被調(diào)用時會顯示此內(nèi)容</slot> ?? ??? ?<slot name="footer">插槽未被調(diào)用時會顯示此內(nèi)容</slot> ?? ?</div> </template>
3.作用域插槽
父組件:
<template> ?? ?<Child> <!-- Child為子組件標簽 --> ?? ??? ?<!-- 插槽內(nèi)容 --> ?? ??? ?<template slot="header"> ?? ??? ??? ?<span v-for="m in data.msg" :key="m"></span> ?? ??? ?</template> ?? ??? ?<template slot="center"> ?? ??? ??? ?<div v-for="m in data.msg" :key="m"></div> ?? ??? ?</template> ?? ??? ?<template slot="footer"> ?? ??? ??? ?<label v-for="m in data.msg" :key="m"></label> ?? ??? ?</template> ?? ?</Child> </template>
子組件:
<template> ?? ?<div> ?? ??? ?<!-- 插槽位置 --> ?? ??? ?<slot :msg="msg">插槽未被調(diào)用時會顯示此內(nèi)容</slot> ?? ?</div> </template> <script> ?? ?export default { ?? ??? ?name: 'Child', ?? ??? ?// 公用數(shù)據(jù) ?? ??? ?data() { ?? ??? ??? ?return { ?? ??? ??? ??? ?msg: ["火鍋", "紅燒肉", "烤羊腿"] ?? ??? ??? ?} ?? ??? ?} ?? ?} </script>
到此這篇關(guān)于Vue默認插槽,具名插槽,作用域插槽定義及使用方法的文章就介紹到這了,更多相關(guān)Vue插槽定義內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue-cli webpack 開發(fā)環(huán)境跨域詳解
本篇文章主要介紹了vue-cli webpack 開發(fā)環(huán)境跨域詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05