vue學習---插槽(slot標籤 與 scope屬性)
阿新 • • 發佈:2021-11-20
插槽
-
作用:讓父元件可以向子元件指定位置插入html結構,也是一種元件間通訊的方式,適用於父元件 ===> 子元件。
-
分類:預設插槽、具名插槽、作用域插槽
-
使用方式:
-
預設插槽:
父元件中: <Category> <div>html結構1</div> </Category> 子元件中: <template> <div> <!-- 定義插槽 --> <slot>插槽預設內容...</slot> </div> </template>
-
具名插槽:
父元件中: <Category> <template slot="center"> <div>html結構1</div> </template> <template v-slot:footer> <div>html結構2</div> </template> </Category> 子元件中: <template> <div> <!-- 定義插槽 --> <slot name="center">插槽預設內容...</slot> <slot name="footer">插槽預設內容...</slot> </div> </template>
-
作用域插槽:
-
理解:資料在元件的自身,但根據資料生成的結構需要元件的使用者來決定。(games資料在Category元件中,但使用資料所遍歷出來的結構由App元件決定)
-
具體編碼:
父元件中: <Category> <template scope="scopeData"> <!-- 生成的是ul列表 --> <ul> <li v-for="g in scopeData.games" :key="g">{{g}}</li> </ul> </template> </Category> <Category> <template slot-scope="scopeData"> <!-- 生成的是h4標題 --> <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4> </template> </Category> 子元件中: <template> <div> <slot :games="games"></slot> </div> </template> <script> export default { name:'Category', props:['title'], //資料在子元件自身 data() { return { games:['紅色警戒','穿越火線','勁舞團','超級瑪麗'] } }, } </script>
-
-