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