Vue 插槽(Slots)全解析2
六、动态插槽名:“插槽名也能动态变”
插槽名可以是动态的(如根据父组件的 data 变化),用 v-slot:[动态变量]
(或简写 #[动态变量]
)实现。
示例:
<!-- 父组件 --> <template> <BaseLayout> <!-- 动态插槽名:根据 currentSlot 的值决定传给哪个插槽 --> <template #[currentSlot]> <p>动态插槽内容</p> </template> </BaseLayout> </template> <script> export default { data() { return { currentSlot: "header" } // 可动态修改为 "footer" 等 } } </script>
当 currentSlot
为“header”时,内容传给 header 插槽;改为“footer”时,自动传给 footer 插槽。
七、作用域插槽:“子组件给内容传数据”
默认情况下,插槽内容(父组件写的)只能访问父组件数据。但有时需要让内容访问子组件数据(如子组件的列表项),此时需用作用域插槽:子组件通过插槽出口“传 props”,父组件的插槽内容“接收 props”。
1. 基础用法:子传值,父接收
-
步骤1:子组件给插槽传 props 在
<slot>
上用v-bind
绑定要传递的数据(类似给组件传 props):<!-- 子组件:MyComponent --> <template> <div> <!-- 给插槽传 props:text 和 count --> <slot :text="greetingMessage" :count="1"></slot> </div> </template> <script> expor