当前位置: 首页 > ai >正文

20250418-vue-作用域插槽

父组件中,插槽的内容无法访问到子组件的状态。

然而在某些场景下,插槽的内容可能想要同时使用父组件域内和子组件域内的数据。要做到这一点,我们需要一种方法来让子组件在渲染时将一部分数据提供给插槽。

办法就是,可以像对组件传递 props 那样,向一个插槽的出口上传递 attributes:

<!-- <MyComponent> 的模板 -->
<div><slot :text="greetingMessage" :count="1"></slot>
</div>

当需要接收插槽 props 时,默认插槽和具名插槽的使用方式有一些小区别。

先展示默认插槽如何接受 props,通过子组件标签上的 v-slot 指令,直接接收到了一个插槽 props 对象:

<MyComponent v-slot="slotProps">{{ slotProps.text }} {{ slotProps.count }}
</MyComponent>

子组件代码

<script>
export default {data() {return {greetingMessage:'hello'}}
}
</script><template><div><slot :text="greetingMessage" :count="1"></slot></div>
</template>

父组件代码

<script>
import MyComponent from './MyComponent.vue'export default {components: { MyComponent },data() {return {}}
}
</script><template><MyComponent v-slot="slotProps">{{ slotProps.text }} {{ slotProps.count }}</MyComponent>
</template>

子组件传入插槽的 props 作为了 v-slot 指令的值,可以在插槽内的表达式中访问。

我们也可以在 v-slot 中使用解构:

<MyComponent v-slot="{ text, count }">{{ text }} {{ count }}
</MyComponent>

具名作用域插槽

具名作用域插槽的工作方式也是类似的,插槽 props 可以作为 v-slot 指令的值被访问到:

v-slot:name="slotProps"。当使用缩写时是这样:

<MyComponent><template #header="headerProps">{{ headerProps }}</template><template #default="defaultProps">{{ defaultProps }}</template><template #footer="footerProps">{{ footerProps }}</template>
</MyComponent>

向具名插槽中传入 props:

<slot name="header" message="hello"></slot>

注意插槽上的 name 是一个 Vue 特别保留的 attribute,不会作为 props 传递给插槽。因此最终 headerProps 的结果是 { message: 'hello' }。

如果同时使用了具名插槽与默认插槽,则需要为默认插槽使用显式的 <template> 标签。尝试直接为组件添加 v-slot 指令将导致编译错误。这是为了避免因默认插槽的 props 的作用域而困惑。例如:

<!-- <MyComponent> template -->
<div><slot :message="hello"></slot><slot name="footer" />
</div>
<!-- 该模板无法编译 -->
<MyComponent v-slot="{ message }"><p>{{ message }}</p><template #footer><!-- message 属于默认插槽,此处不可用 --><p>{{ message }}</p></template>
</MyComponent>

为默认插槽使用显式的 <template> 标签有助于更清晰地指出 message 属性在其他插槽中不可用:

<MyComponent><!-- 使用显式的默认插槽 --><template #default="{ message }"><p>{{ message }}</p></template><template #footer><p>Here's some contact info</p></template>
</MyComponent>

http://www.xdnf.cn/news/1985.html

相关文章:

  • MySQL 详解之备份与恢复策略:数据安全的最后一道防线
  • BT151-ASEMI无人机专用功率器件BT151
  • 软件测试入门学习笔记
  • 蓝桥杯 5. 交换瓶子
  • IP SSL证书常见问题助您快速实现HTTPS加密
  • Infortrend普安存储 KS 私有云方案,构建生产线AOI光学检测数据的高速处理平台
  • Kafka生产者架构深度剖析
  • 【合新通信】浸没式液冷光模块与冷媒兼容性测试技术报告
  • 线程池参数配置
  • flutter getx 中.obs 的方法refresh方法
  • OpenAI 最新 o3 集成到 Cursor 和 Cline 工作流程中
  • 【leetcode刷题日记】lc.73-矩阵置零
  • U-Mail邮件加速服务:全球链路加速,安全稳定收发
  • OpenCV中的SIFT特征提取
  • ubuntu 20.04 编译运行lio-sam,并保存为pcd
  • 《Piper》皮克斯技术解析:RIS系统与云渲染如何创造奥斯卡级动画短片
  • XYNU2024信安杯-REVERSE(复现)
  • 面试踩过的坑
  • Shell脚本-while循环语法结构
  • 2025 年导游证报考条件新政策解读与应对策略
  • 为何 RAG 向量存储应优先考虑 PostgreSQL + pgvector 而非 MySQL?
  • Linux:进程间通信->匿名管道实现内存池
  • C/C++线程详解
  • Kafka 架构设计和组件介绍
  • 无人机环境适应性与稳定性技术要点!
  • 高效DCDC电源芯片在运动控制器中的应用:设计考量、性能评估与可靠性分析
  • PySide与Qt工具链的深度整合
  • 传统中台的重生——云原生如何重塑政务系统后端架构
  • websheet 之 单元格
  • 计算机网络笔记(十一)——2.4信道复用技术