slot插槽
啥是插槽啊?一句话:让父组件可以向子组件的指定位置插入html结构,也是一种组件间的通信方式.
默认插槽
挖一个坑,等着组件的使用者进行填充
<template> <div> <h3>{{title}}</h3> <!-- 挖个坑 --> <slot></slot> </div> </template> <script> export default { name: 'typeslot', props: { title:String }, }; </script>
<template> <typeslot title="美食"> <img src="../public/img/abe1eea3ca79fc28-c577ebdcb0f3dbcc-257e2ecb7fd1c47961a553ca5ef4505e.jpg" style="width:50px"> </typeslot> <typeslot titke="购物"> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> </typeslot> <typeslot title="电影"> <img src="../public/img/abe1eea3ca79fc28-c577ebdcb0f3dbcc-7bcd14d52919cba85df3696608531259.jpg" style="width:50px"> </typeslot> </template> <script> import typeslot from './components/TypeSlot.vue' export default { name: 'App', components: { typeslot } } </script>
结果:
具名插槽
当年挖坑,给每个坑取了个名字,等到填坑,说明白把哪个结构放在哪个坑
子组件:
<slot name="center"></slot> <slot name="footer"></slot>
父组件:
<typeslot title="美食"> <template v-slot:center> <!-- 把图片放到main插槽中 --> <img src="../public/img/abe1eea3ca79fc28-c577ebdcb0f3dbcc-257e2ecb7fd1c47961a553ca5ef4505e.jpg" style="width:50px"> </template> <template #footer> <!-- 把a标签放到footer插槽中 --> <a >你好</a> </template> </typeslot>
最新写法:得使用template包裹 v-slot:名字,不需要双引号;也可以简写为#名字
而且template标签不会变成div元素
结果:
作用域插槽
数据不在使用者那里,在子组件那边,那么使用者(父组件)怎么展示数据?
作用域插槽使用步骤:
1.在组件那边绑定数据
2.使用者必须在template中,然后使用v-slot拿到数据,最后运用数据,什么样的形式,什么样的数据展示出来,由使用者绝定.
子组件
<!-- 绑定数据--> <slot :dataList="dataList"></slot> 数据: data(){ return{ dataList:['小猫','小狗','小兔'] }
父组件:
<typeslot title="美食"> <template v-slot="abc"> <!-- 以无序列表形式展示 --> <ul> <li v-for="(item,index) in abc.dataList" :key="index">{{item}}</li> </ul> </template> </typeslot> <typeslot title="购物"> <!-- 以有序列表展示 --> <template v-slot="abc"> <ol> <li v-for="(item,index) in abc.dataList" :key="index">{{item}}</li> </ol> </template> </typeslot>
结果:
补充:
1.如果使用
2.scope与style里的scoped区别:style标签里的scoped作用的是当前页面的元素
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix