vue之slot,組件標簽嵌套
插槽(Slot),在各種vue的ui插件中,經常見到的多個組件標簽相互嵌套(如下)就是以此為基礎的。
<el-col > <el-checkbox > </el-col>
而我們也經常會用到這種場景,例如封裝一個邊框樣式的組件,組件中的內容,可以通過這種方式制作,或者將子組件提取到父組件中進行操作等等。
slot分為兩種情況,匿名和具名。
1.匿名
例子:
子組件:
<div> <h2>我是子組件的標題</h2> <slot></slot> /*這里插入父組件在引用子組件內部的內容*/ </div>
父組件:
<div> <h1>我是父組件的標題</h1> <my-component> <p>這是一些初始內容</p> <p>這是更多的初始內容</p> </my-component> </div>
父組件p標簽的位置也可以放一些其他組件。my-component標簽中的內容,會插入到該組件slot標簽的位置。
當渲染后,就會變成:
<div> <h1>我是父組件的標題</h1> <div> <h2>我是子組件的標題</h2> <p>這是一些初始內容</p> <p>這是更多的初始內容</p> </div> </div>
2.具名:
具名slot其實就是對匿名slot的補充,它可以做到將組件插入到子組件的指定位置。
例子:
子組件:
<div> <slot name="header"></slot> <slot name="footer"></slot> <slot></slot> </div>
父組件:
<my-component> <p>Lack of anonymous slot, this paragraph will not shown.</p> <p slot="footer">Here comes the footer content</p> <p slot="header">Here comes the header content</p> </my-component>
渲染結果:
<div> <p>Here comes the header content</p> <p>Here comes the footer content</p> <p>Lack of anonymous slot, this paragraph will not shown.</p> </div>
參考自:https://blog.csdn.net/u014628388/article/details/76100400