vue的插槽slot

vue的插槽slot什么是插槽 插槽 slot 是 vue 提出来的一个概念 正如名字一样 插槽用于决定将所携带的内容 插入到指定的某个位置 从而使模版分块 具有模块化的特质和更大的重用性 插槽显不显示 怎样显示是由父组件来控制的 而插槽在哪里显示就由子组件来进行

大家好,欢迎来到IT知识分享网。

什么是插槽?

  • 插槽(slot)是vue提出来的一个概念,正如名字一样,插槽用于决定将所携带的内容,插入到指定的某个位置,从而使模版分块,具有模块化的特质和更大的重用性。
  • 插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制。

怎么用插槽?

1、默认插槽

//父组件 <template> <view> 我是父组件 <dfSlot>//dfSlot是子组件 <view class="slot-cont"> 我是父组件的插槽内容 </view> </dfSlot> </view> </template> //子组件 <template> <view class="df-slot"> 我是子组件内容dfslot组件 <slot></slot> </view> </template> 
vue的插槽slot

2、具名插槽

//子组件(slotTwo) <template> <div class="slottwo"> <div>slottwo</div> <slot name="header"></slot> <slot></slot> <slot name="footer"></slot> </div> </template> //父组件 <template> <div> 我是父组件 <slot-two> <template #header> <p>我是name为header的slot</p> </template> <template #default> <p>啦啦啦,啦啦啦,我是卖报的小行家</p> </template> // 要这样写 <template #footer> <p>我是name为footer的slot</p> </template> </slot-two> // 或者用以下的格式(注意不能混着用) <slot-two> <template v-slot:header> <p>我是name为header的slot</p> </template> <template v-slot:default> <p>啦啦啦,啦啦啦,我是卖报的小行家</p> </template> <template v-slot:footer> <p>我是name为footer的slot</p> </template> </slot-two> </div> </template> //在父组件中使用template并写入对应的slot值来指定该内容在子组件中显示的位置 //(当然也不用必须写到template), //没有对应值的其他内容会被放到子组件中没有添加name属性的slot中 // 但是没有对应的内容,有时候我实际操作,不显示,存疑问「建议都写名字吧」

3、插槽的默认内容

可以在子组件的slot标签中写入内容,当父组件没有写入内容时会显示子组件的默认内容,当父组件写入内容时,会替换子组件的默认内容

vue的插槽slot

//父组件 <template> <div> 我是父组件 <slot-two></slot-two> </div> </template> //子组件 <template> <div class="slottwo"> <slot>我不是卖报的小行家</slot> </div> </template>

4、编译作用域

//父组件 <template> <div> 我是父组件 <slot-two> <p>{{name}}</p> </slot-two> </div> </template> <script> export default { data () { return { name: 'Jack' } } } </script> //子组件 <template> <div class="slottwo"> <slot></slot> </div> </template> 
vue的插槽slot

5、作用域插槽

//子组件(在子组件的slot标签上绑定需要的值) <template> <div> 我是作用域插槽的子组件 <slot :data="user"></slot>//(在子组件的slot标签上绑定需要的值) </div> </template> <script> export default { name: 'slotthree', data () { return { user: [ {name: 'Jack', sex: 'boy'}, {name: 'Jone', sex: 'girl'}, {name: 'Tom', sex: 'boy'} ] } } } </script> //父组件「」 <template> <div> 我是作用域插槽 <slot-three> <template slot-scope="user">//在父组件中使用 slot-scope属性 //user.data就是子组件传过来的值 <div v-for="(item, index) in user.data" :key="index"> {{item}} </div> </template> </slot-three> </div> </template> 
vue的插槽slot

原文链接:
https://www.cnblogs.com/loveyt/p/9946450.html

https://blog.csdn.net/xiaolinlife/article/details/

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/183661.html

(0)
上一篇 2025-07-18 07:20
下一篇 2025-07-18 07:26

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信