Vue3具名插槽


一般不使用具名插槽時,都是這樣使用

子組件 MyBar

<template> 

  <slot>
    <button>點我</button> //如果父組件在使用子組件的時沒有寫入標簽或內容就會默認顯示button
  </slot> </template>

父組件 MySideBar

<template>
    <my-bar>
            寫入想要的標簽或內容
    </my-bar>
</template>

但如果子組件有多個solt插槽就是會同時顯示多個相同的內容 

所以需要用到具名插槽來顯示不同的內容

子組件 MyBar

<template>
        <slot name='one'> //給子組件的插槽起名字
            
        </slot>
        <slot name='two'>
            
        </slot>
        <slot>
            我就是可以可以匹配default的
        </slot>
</template>

父組件 MySideBar

<template>
  <div>
    <my-bar> //子組件
        <a href="" slot="one">提交</a>   //這是vue2的寫法,在vue3里不支持
    </my-bar>

  //在vue3下要使用具名插槽必須先在外面加層模版 template
  v-slot:子組件slot上name的名字
  v-slot:default(匹配沒有給子組件取名字的)
#子組件slot名字

  <my-bar> //子組件
    <template v-slot:default> //匹配無名字的slot
    
    </template>
    <template v-slot:two> //匹配名字是two的slot
      
    </template>
    <template #two> //簡寫
      
    </template>
  </my-bar>
  
  </div>

   </template>

 


免責聲明!

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



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