vue 三种类型的插槽
插槽,用于在组件中定义可替换的内容区域。通过插槽,父组件可以向子组件传递内容(如HTML、文本、其他组件等),从而实现更灵活和可复用的组件设计。
一、默认插槽
默认插槽是最简单的插槽形式,父组件传递的内容会替换子组件中的<slot>标签。
子组件Child
<template><div class="child"><h3>子组件标题</h3><slot>默认内容</slot></div>
</template>
父组件
<template><Child><p>这是父组件传递的内容</p><Child/>
</template>
渲染结果
<div class="child"><h3>子组件标题</h3><p>这是父组件传递的内容</p>
</div>
如果父组件没有传递内容,<slot>中的默认内容(“默认内容”)会显示
二、具名插槽
具名插槽允许子组件定义多个插槽区域,父组件可以通过v-slot指定内容插入的位置。
子组件Child
<template><div class="child"><header><slot name="header">默认头部</slot></header><main><slot>默认内容</slot></main><footer><slot name="footer">默认尾部</slot></footer></div>
</template>
父组件
<template><Child><template v-slot:header><h1>自定义头部</h1></template><p>这是主内容</p><template v-slot:footer><p>自定义尾部</p></template></Child>
</template>
渲染结果
<div class="child"><header><h1>自定义头部</h1></header><main><p>这是主内容</p></main><footer><p>自定义尾部</p></footer>
</div>
父组件通过v-slot:name指定内容插入的位置;未命名的内容会插入到默认插槽中
三、作用域插槽
作用域插槽允许父组件访问子组件的数据,从而实现更灵活的内容渲染。
子组件Child
<template><div class="child"><slot :user="user" :msg="msg"></slot></div>
</template><script>
export default {data() {return {user: {name: 'Alice',age: 25,},msg: '吃饭'}}
}
</script>
父组件
<template><Child v-slot="{ user, msg }"><p>姓名: {{ user.name }}</p><p>年龄: {{ user.age }}</p>{{ msg }}</Child>
</template>
渲染结果
<div class="child"><p>姓名:Alice</p><p>年龄: 25</p>吃饭
</div>
子组件通过:user="user"将数据传递给插槽;父组件通过v-slot="{ user }"接收数据并渲染内容
四、高级用法
1.动态插槽名
通过动态插槽名,可以根据数据动态选择插槽
子组件
<template><div class="child"><slot name="dynamic">默认内容</slot></div>
</template>
父组件
<template><Child><template v-slot:[slotName]><p>这是动态插槽内容</p></template></Child>
</template>export default {data() {return {slotName: 'dynamic',}}
}
2.插槽的缩写
默认插槽的缩写:#default
具名插槽的缩写:#name
<template><Child><template #header><h1>自定义头部</h1></template><template #default><p>这是主内容</p></template><template #footer><p>自定义尾部</p></template></Child>
</template>
