Vue插槽详解(匿名,具名,作用域)
v-slot 指令自 Vue 2.6.0 起被引入,提供更好的支持 slot 和 slot-scope 特性的 API 替代方案:https://cn.vuejs.org/v2/guide/components-slots.html
1.单个插槽 | 匿名插槽
1.1<navigation-link>
子组件定义为:
<a v-bind:href="url" class="nav-link"> <slot></slot> </a>
1.2父组件像以下这样使用<navigation-link>子组件:
<navigation-link url="/profile"> Your Profile </navigation-link>
1.3渲染出来的 HTML 将会是:
<a v-bind:href="url" class="nav-link"> Your Profile </a>
2.具名插槽
需要多个插槽时,可以利用<slot>
元素的一个特殊的特性:name来定义具名插槽
2.1<base-layout>子组件模板定义:
<div class="container"> <header> <slot name="header"></slot> </header> <main> <slot></slot> </main> <footer> <slot name="footer"></slot> </footer> </div>
2.2.1父组件使用子组件<base-layout>,节点上使用slot特性:
<base-layout> <h1 slot="header">Here might be a page title</h1> <p>A paragraph for the main content.</p> <p>And another one.</p> <p slot="footer">Here's some contact info</p> </base-layout>
2.2.2也可在内容外层套一个节点,并在外层节点上使用slot特性:
<base-layout> <template slot="header"> <h1>Here might be a page title</h1> </template> <p>A paragraph for the main content.</p> <p>And another one.</p> <template slot="footer"> <p>Here's some contact info</p> </template> </base-layout>
2.3渲染出来的 HTML 都将会是:
<div class="container"> <header> <h1>Here might be a page title</h1> </header> <main> <p>A paragraph for the main content.</p> <p>And another one.</p> </main> <footer> <p>Here's some contact info</p> </footer> </div>
3.作用域插槽——带数据的插槽
单个插槽和具名插槽中插槽上不绑定数据,所以父组件提供的模板既要包括样式又要包括数据,而作用域插槽是子组件提供数据,父组件只需要提供一套样式
3.1子组件:
<template> <div class="child"> <h3>这里是子组件</h3> // 作用域插槽 <slot :data="data"></slot> </div> </template> export default { data: function(){ return { data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba'] } } }
3.2父组件:
<template> <div class="father"> <h3>这里是父组件</h3> <!--第一次使用:用flex展示数据--> <child> <template slot-scope="user"> <div class="tmpl"> <span v-for="item in user.data">{{item}}</span> </div> </template> </child> <!--第二次使用:用列表展示数据--> <child> <template slot-scope="user"> <ul> <li v-for="item in user.data">{{item}}</li> </ul> </template> </child> <!--第三次使用:直接显示数据--> <child> <template slot-scope="user"> {{user.data}} </template> </child> <!--第四次使用:不使用其提供的数据, 作用域插槽退变成匿名插槽--> <child> 我就是模板 </child> </div> </template>
3.3结果如图:
匿名插槽和具名插槽详情见:https://cn.vuejs.org/v2/guide/components-slots.html#作用域插槽
作用域插槽详情见:https://segmentfault.com/a/1190000013277423
关于作用域插槽看完上面还是有点懵的,建议看看这篇文章
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗