前言
slot可以在子組件中開啟插槽,在父組件引用該組建時,可以定義這個插槽內(nèi)要展現(xiàn)的功能或模塊,下面話不多說了,來一起看看詳細的介紹吧
1.單個slot
子組件中在相應(yīng)位置寫slot標簽,父組件在引用子組件時,在子組件標簽內(nèi)寫要插入插槽的元素;
還可以設(shè)置slot在父組件沒有設(shè)置插槽時,子組件的插槽默認顯示內(nèi)容;
父組件.vue
<template> <div class="home"> <child-componment> <p> 這是父組件的slot替代內(nèi)容! </p> </child-componment> </div></template><script>import childComponment from '@/components/childComponment.vue'export default { name: "home", components:{ childComponment }, data(){ return { message: '' } }};</script>子組件childComponment.vue
<template> <div class="childComponment"> <h2>這是子組件childComponment!</h2> <slot> <span style="color: red;">如果父組件沒有插入內(nèi)容,我這樣可以設(shè)置默認的顯示內(nèi)容</span> </slot> </div></template><script>export default { name: "childComponment", data(){ return { message: '' } }};</script>2.具名slot(同時使用多個插槽)
給slot指定一個名稱,可以分發(fā)多個slot插槽,但是只能有一個無名slot;
父組件的slot插槽內(nèi)容,不寫slot="xxx"的都會插到子組件的無名slot中;
如果沒有指定無名slot(默認slot),父組件內(nèi)多余的內(nèi)容將會被拋棄。
<template> <div class="home"> <child-componment> <h1 slot="header"> 父組件的header </h1> <h6 slot="footer">父組件的footer</h6> <h6>父組件的無名slot-1</h6> <p> 父組件的無名slot-2 </p> </child-componment> </div></template><script>import childComponment from '@/components/childComponment.vue'export default { name: "home", components:{ childComponment }, data(){ return { message: '' } }};</script>子組件
<template> <div class="childComponment"> <span>這是子組件childComponment的正常內(nèi)容!</span> <div class="header"> <slot name="header"> <span style="color: red;">子組件默認header-slot</span> </slot> </div> <div class="container"> <!-- 如果沒有指定無名slot(默認slot),父組件內(nèi)多余的內(nèi)容將會被拋棄 --> <slot> <span style="color: red;">子組件默認無名slot</span> </slot> </div> <div class="footer"> <slot name="footer"> <span style="color: red;">子組件默認footer-slot</span> </slot> </div> </div></template><script>export default { name: "childComponment", data(){ return { message: '' } }};</script><style scoped>.childComponment{ font-size: 16px;}.header{ height: 100px; border:1px solid red; color: red;}.container{ height: 500px; border: 1px solid black; color: black;}.footer{ height:100px; border: 1px grey solid; color: grey;}</style>
新聞熱點
疑難解答
圖片精選