Vue-Slot 插槽詳解
什么是插槽
定義
實現(xiàn)功能
- 將自定義內(nèi)容插入 組件中指定的位置
自定義內(nèi)容 (包括不限于以下)
- HTML代碼
- 文本內(nèi)容
- 組件 ..
插槽的作用
- 父組件,子組件的狀態(tài)數(shù)據(jù)傳遞 (作用域插槽)
- 提供靈活的,私人訂制版組件
插槽的分類
默認插槽
代碼
//定義組件 Card <template> <div class="cardContainer"> <h3>Card組件</h3> <slot>我是一個插槽</slot> </div> </template> /****************************************/ //父組件使用Card組件 <template> <div id="app"> //使用Card組件 <Card> <template> //模板中的內(nèi)容會替換 Card 組件中 <slot></slot>內(nèi)容 </template> </Card> </div> </template>
具名插槽
代碼
//Vue解析模版時,默認情況下,未指定名稱的插槽默認值為default //同一個組件中,存在多個未命名插槽,當僅使用一個時,會將內(nèi)容插入所有插槽中 //定義具名插槽 <template> <div class="cardContainer"> <slot name="content"> 我是插槽1 </slot> <h4>更多內(nèi)容 敬請關(guān)注...</h4> <slot name="footer">我是個插槽2</slot> </div> </template> //使用具名插槽 <template> <div id="app"> <Card title="電影"> <!-- v-slot:插槽名 --> <template v-slot:content> 我在使用名稱:content的插槽 </template> </Card> </div> </template>
作用域插槽
使用場景
父組件在向插槽中插入內(nèi)容時需要使用子組件中定義的數(shù)據(jù)時
//作用域插槽 子組件 <template> <div class="cardContainer"> <h3>{{ title }}</h3> <slot name="content" :content="content"> 我是插槽1 </slot> <!-- 設(shè)置一個插槽 --> <h4>更多內(nèi)容 敬請關(guān)注...</h4> <slot name="footer">我是個插槽2</slot> <span></span> </div> </template> <script> export default { name: "Card", data() { return {}; }, props: { title: String, }, computed: { content() { if (this.title === "電影") { return ["恐怖", "驚悚", "喜劇"]; } if (this.title === "游戲") { return ["單機", "聯(lián)機"]; } }, }, }; </script> <style scoped> .cardContainer { width: 400px; margin-left: 20px; background-color: aquamarine; } h3 { text-align: center; background-color: bisque; } </style>父組件
<template> <div id="app"> <Card title="電影"> <!-- v-slot:插槽名="插槽屬性綁定值 ,類型 Object" --> <template v-slot:content="contentInfo"> <ul> <li v-for="item in contentInfo.content" :key="item">{{ item }}</li> </ul> </template> </Card> <Card title="游戲"> <template v-slot:content> <ol> <li>單機</li> <li>聯(lián)機</li> </ol> </template> </Card> </div> </template> <script> import Card from "./components/slot組件/Card"; export default { name: "App", components: { Card, }, mounted() {}, }; </script> <style> #app { display: flex; justify-content: space-around; } </style>
注意事項
- 父級模板里的所有內(nèi)容都是在父級作用域中編譯的;子模板里的所有內(nèi)容都是在子作用域中編譯的。
- v-slot 指令的使用區(qū)別與其他指令的語法形式
- v-if= “”
- v-slot:插槽名 (vue @2.6+版本新語法)