插槽的概念
插槽就是子组件中的提供给父组件使用的一个占位符,用slot标签 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的slot标签。简单理解就是子组件中留下个“坑”,父组件可以使用指定内容来补“坑”。
默认插槽
<!-- 子组件 ChildComponent.vue -->
<template><div><h2>子组件标题</h2><slot>这是默认内容,当父组件不提供内容时显示</slot></div>
</template><!-- 父组件使用 -->
<child-component><p>这是父组件插入的内容</p>
</child-component>
具名插槽
》》当需要多个插槽时,可以使用具名插槽:
<!-- 子组件 Layout.vue -->
<template><div><header><slot name="header"></slot></header><main><slot></slot> <!-- 默认插槽 --></main><footer><slot name="footer"></slot></footer></div>
</template><!-- 父组件使用 -->
<layout><template slot="header"><h1>页面标题</h1></template><p>主要内容区域</p> <!-- 默认插槽内容 --><template v-slot:footer><p>页脚信息</p></template>
</layout>
作用域插槽
作用域插槽的使用情景:当数据在组件(子)自身,但根据数据生成的结构需要组件(父)使用者来定,我们则可以使用作用域插槽
<!-- 子组件 ScopedComponent.vue -->
<template><div><slot :user="user" :age="age"></slot></div>
</template><script>
export default {data() {return {user: '张三',age: 25}}
}
</script><!-- 父组件使用 -->
<scoped-component><template v-slot:default="slotProps"><p>用户名: {{ slotProps.user }}</p><p>年龄: {{ slotProps.age }}</p></template>
</scoped-component>