作用域插槽是Vue中子组件向父组件传递响应式数据供渲染的自然方式,通过<slot>绑定数据、v-slot解构接收,实现单向、只读、响应式的渲染委托。

作用域插槽是 Vue 实现「子传父数据用于渲染」最自然的方式——它不靠事件、不改 props,而是让子组件把数据“托付”给插槽,由父组件决定怎么展示。
子组件:用 <slot> 绑定要暴露的数据
在子组件模板里,给 <slot> 添加属性(如 :user="userInfo"),这些属性会作为对象参数传给父组件。数据必须是响应式的(ref、reactive 或 computed),才能保持更新。
- 默认插槽写法(单插槽场景):
<slot :item="currentItem" :index="currentIndex"></slot> - 具名插槽写法(多插槽更清晰):
<slot name="footer" :count="list.length" :loading="isLoading"></slot>
父组件:用 v-slot 解构接收并使用
父组件通过 <template #xxx="{ prop1, prop2 }"> 接收子组件传来的对象,直接解构出字段,写在模板中即可渲染。参数名可自定义,不依赖子组件内部变量名。
- 默认插槽:
<template #default="{ item, index }">{{ index }}. {{ item.title }}</template> - 具名插槽:
<template #footer="{ count }">共 {{ count }} 条</template> - 简写支持解构默认值:
<template #default="{ item = { title: '暂无' } }">{{ item.title }}</template>
关键细节:它不是双向通信,也不触发副作用
作用域插槽本质是一次「渲染委托」:子组件调用父提供的插槽函数,把自身数据当参数传入;Vue 自动保证响应性——只要传的是响应式数据,父模板里的表达式就会随数据变化重新求值。
立即学习“前端免费学习笔记(深入)”;
- 父组件无法修改子组件传来的数据(只读)
- 不需要
$emit、ref或额外监听 - 插槽内容在父组件作用域编译,只能访问父组件的数据和方法
Vue 3 中的写法统一且简洁
Vue 3 废弃了 slot-scope 和 scope,只保留 v-slot(支持简写 #)。Composition API 下配合 setup() 返回数据,逻辑更直观:
- 子组件
setup()中:const users = ref([{ id: 1, name: 'Tom' }]); return { users }; - 模板中:
<slot :users="users"></slot> - 父组件直接消费:
<template #default="{ users }"><div v-for="u in users" :key="u.id">{{ u.name }}</div></template>


















