理解vue中的slot與slot-scope


vue的slot和slot-scope

對於vue的slot和slot-scope在寫vue項目的時候總是很朦朧!vue的文檔有比較精簡。vue slot文檔

先說說slot是啥!都知道的slot叫插槽,其實也好理解,通俗點就是插到某一部分(-_-||)PS:想象一下電腦,有插CPU的,有插顯卡的,有插內存的,有插硬盤的~。術語的話就是占位符吧(至少我是這么理解的)。作用就是內容的分發。

值得注意的是:內容要寫在父組件中,然后分給需要的子組件。當slot多個時,可以通過name來加以區分,這就是所謂的具名插槽

舉個栗子:

  • 默認插槽

父組件:

 1 <template>
 2     <div class="father">
 3         <h3>這里是菜單</h3>
 4         <child>
 5             <div class="list">
 6               <li>口水雞</li>
 7               <li>口水鴨</li>
 8               <li>口水豬</li>
 9               <li>口水驢</li>
10               <li>口水羊</li>
11               <li>口水牛</li>
12             </div>
13         </child>
14     </div>
15 </template>

  子組件:

 

1 <template>
2     <div class="child">
3         <h3>這里是餐桌點餐</h3>
4         <slot></slot>
5     </div>
6 </template>

 

  • 具名插槽 PS:官網案例

  父組件:

 

 1 <base-layout>
 2   <template slot="header">
 3     <h1>Here might be a page title</h1>
 4   </template>
 5 
 6   <p>A paragraph for the main content.</p>
 7   <p>And another one.</p>
 8 
 9   <template slot="footer">
10     <p>Here's some contact info</p>
11   </template>
12 </base-layout>

  子組件:

1 1 <base-layout>
2 2   <h1 slot="header">Here might be a page title</h1>
3 3 
4 4   <p>A paragraph for the main content.</p>
5 5   <p>And another one.</p>
6 6 
7 7   <p slot="footer">Here's some contact info</p>
8 8 </base-layout>

  這兩者就是多了個name,不過一般都會加上name,項目中不會只有一個插槽。

  再說說slot-scope,跟官網一樣,我個人覺得slot-scope就是作用域插槽。並且他是接收子組件傳來的數據。

  舉個栗子:

  • 作用域插槽

  父組件:

 1 <template>
 2     <div class="father">
 3     <h3>這里是父組件</h3>
 4     <slot-scope-child>
 5         <template slot-scope="user">
 6             <ul>
 7                 <li v-for="(item, index) in user.data" :key="index">{{item}}</li>
 8             </ul>
 9         </template>
10     </slot-scope-child>
11   </div>
12 </template>
13 <script>
14 import SlotScopeChild from '@/common/SloteScopeChild'
15 export default {
16     components: {
17         SlotScopeChild
18     }
19 }
20 </script>
21 <style scoped>
22 </style>

 

  子組件:

 1 <template>
 2   <div class="child">
 3     <h3>這里是子組件</h3>
 4     <slot :data="data"></slot>
 5   </div>
 6 </template>
 7 <script>
 8 export default {
 9     data: function(){
10       return {
11         data: ['空空如也','悟空','成都','七月上','病變','走馬']
12       }
13     }
14 }
15 </script>

  然后你就會發現,子組件里面的數據會展示出來。這也就是slot-scope。就是帶着數據跑。數據在子組件,然后綁到父組件,父組件就可以使用了。這個在elementUI中展示的很好。

  這大概就是我的理解~新手勿怪!錯誤請多包涵指正。

 

現在再看,2-21號追加的內容,我承認會給我分銷,但是內容真的很好。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM