vue作用域插槽-cnblog
- 使用场景:父组件需要使用到子组件的data时
例子
-
父组件有list数组,传递给子组件,子组件将数组中的属性全部显示出来,但是用什么标签显示这些属性不确定(使用插槽)
-
父组件传递插槽内容过去替换子组件的slot,问题来了,内容是数组项的第几个呢?
-
子组件将数组项内容回传父组件,通过插槽(作用域插槽)
父组件
- 核心代码
<MyTable :arr="list"> <template v-slot="scope"> <img style="width: 100px;" :src="scope.row.headImgUrl" alt=""> </template> </MyTable>
<template> <div> <MyTable :arr="list"></MyTable> <MyTable :arr="list"> <!-- scope: {row: obj} --> <template v-slot="scope"> <a :href="scope.row.headImgUrl">{{ scope.row.headImgUrl }}</a> </template> </MyTable> <MyTable :arr="list"> <template v-slot="scope"> <img style="width: 100px;" :src="scope.row.headImgUrl" alt=""> </template> </MyTable> </div> </template> <script> import MyTable from "../components/06/MyTable"; export default { components: { MyTable, }, data() { return { list: [ { name: "小传同学", age: 18, headImgUrl: "http://yun.itheima.com/Upload/./Images/20210303/603f2d2153241.jpg", }, { name: "小黑同学", age: 25, headImgUrl: "http://yun.itheima.com/Upload/./Images/20210304/6040b101a18ef.jpg", }, { name: "智慧同学", age: 21, headImgUrl: "http://yun.itheima.com/Upload/./Images/20210302/603e0142e535f.jpg", }, ], }; }, }; </script> <style> </style>
子组件
<template> <div> <table border="1"> <thead> <tr> <th>序号</th> <th>姓名</th> <th>年龄</th> <th>头像</th> </tr> </thead> <tbody> <tr v-for="(obj, index) in arr" :key="index"> <td>{{ index + 1 }}</td> <td>{{ obj.name }}</td> <td>{{ obj.age }}</td> <td> <slot :row="obj"> <!-- 默认值给上,如果使用组件不自定义标签显示默认文字 --> {{ obj.headImgUrl}} </slot> </td> </tr> </tbody> </table> </div> </template> <script> export default { props: { arr: Array } } </script>
分类:
前端解决方案
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!