赞
踩
默认插槽是最基本的形式,用于插入任何未明确命名的内容。
子组件 (Child.vue
) 示例:
- <template>
- <div class="wrapper">
- <header>这是头部</header>
- <slot></slot> <!-- 默认插槽位置 -->
- <footer>这是尾部</footer>
- </div>
- </template>
父组件使用示例:
- <child>
- <p>这里是父组件插入的默认内容</p>
- </child>
具名插槽允许你有选择性地插入内容到组件的特定位置。
子组件 (Child.vue
) 示例:
- <template>
- <div class="container">
- <slot name="header"></slot>
- <slot name="main"></slot>
- <slot name="footer"></slot>
- </div>
- </template>
父组件使用示例
- <child>
- <template v-slot:header>
- <h2>自定义头部</h2>
- </template>
- <template v-slot:main>
- <p>主要内容区域</p>
- </template>
- <template v-slot:footer>
- <p>版权信息</p>
- </template>
- </child>
作用域插槽可以接收来自子组件的数据,使插槽内容能基于这些数据动态变化。
子组件 (Child.vue
) 示例:
- <template>
- <div>
- <slot v-bind:user="userData"></slot>
- </div>
- </template>
-
- <script>
- export default {
- data() {
- return {
- userData: { name: '张三', age: 25 }
- };
- }
- };
- </script>
父组件使用示例:
- <child>
- <template v-slot="{ user }">
- <p>姓名:{{ user.name }}</p>
- <p>年龄:{{ user.age }}</p>
- </template>
- </child>
slot
和 slot-scope
,而Vue 3.x 及更高版本推荐使用 v-slot
语法糖。通过合理使用插槽,你可以设计出高度可复用和灵活的组件。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。