vue slots 組件的組合/分發(fā)實例
使用slots 分發(fā)內(nèi)容
使用組件時常常會有組件組合使用的情況,如下:
<componentA> <componentB></componentB> <componentC></componentC> </componentA>
直接套用組件的話,父級組件會將子級組件覆蓋掉,不能實現(xiàn)需求的效果,為了實現(xiàn)該效果就需要使用 slots來內(nèi)容分發(fā)
slots的使用方法如下:
<body> <div id="app"> <app> <child></child> <child2></child2> </app> </div> </body> <script> Vue.component('app',{ template:'\ <div>\ <slot>沒有則顯示這個</slot>\ <li>111</li>\ <li>222</li>\ <li>333</li>\ </div>\ ', }) var app=new Vue({ el:'#app', components:{ 'child':{ template:'<div>hello word</div>' }, 'child2':{ template:'<div>hello vue js</div>' } } }) </script>
<app></app>標簽沒有引入其他組件時顯示為圖1,有其他組件時顯示為圖2
同時可以實測到可以引入多個并列的組件,組件會依次顯示
但是這只能解決單個 組件的引入 ,實際應(yīng)用中需要多個應(yīng)用的組件會在多個位置,為了解決這個問題,就得確定slot位置的唯一性為了確定slot 的vue 中可以給slot 添加行內(nèi) name來識別 ,
需要注意的是:同一父級下的slot 添加行內(nèi) name必須保證唯一;
子組件下的slot 的name 是可以與父級組件的slot name 重復的,及每一級具有相對獨立性。
代碼效果圖如下:
<body> <div id="app"> <app> <child slot="slot1"> </child> <div slot="slot2">How to use slot?</div> </app> </div> </body> <script> Vue.component('app',{ template:'\ <div>\ <slot name="slot1">沒有則顯示這個</slot>\ <li>111</li>\ <li>222</li>\ <slot name="slot2">沒有則顯示這個</slot>\ <li>333</li>\ </div>\ ', }) var app=new Vue({ el:'#app', components:{ 'child':{ template:'<div>hello word\ <li>22222</li>\ </div>' }, 'child2':{ template:'<div>hello vue js</div>' } } }) </script>
以上這篇vue slots 組件的組合/分發(fā)實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue 實現(xiàn)根據(jù)data中的屬性值來設(shè)置不同的樣式
這篇文章主要介紹了vue 實現(xiàn)根據(jù)data中的屬性值來設(shè)置不同的樣式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08vue+axios實現(xiàn)文件下載及vue中使用axios的實例
這篇文章主要介紹了vue+axios實現(xiàn)文件下載及vue中使用axios的實例,需要的朋友可以參考下2018-09-09vue-cli3+echarts實現(xiàn)漸變色儀表盤組件封裝
這篇文章主要為大家詳細介紹了vue-cli3+echarts實現(xiàn)漸變色儀表盤組件封裝,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03