Vue穿梭框通过作用域插槽实现左右列表自定义模板,左侧传item/index/moveToRight,右侧传item/index/moveToLeft,插槽名建议left-item/right-item,子组件提供默认内容兜底,父组件用v-slot解构使用。

Vue 组件插槽实现穿梭框左右列表项的自定义模板,核心是用 作用域插槽(scoped slot) 把每条数据项和操作方法暴露给父组件,让使用者自由控制渲染结构。
左右两侧都用作用域插槽接收 item 数据
在穿梭框子组件中,左右两个列表(如 leftList 和 rightList)分别用 v-for 渲染时,为每个 <slot> 传入当前项和上下文信息:
- 左侧列表插槽:传入
item、index、moveToRight方法 - 右侧列表插槽:传入
item、index、moveToLeft方法 - 插槽名建议统一为
item,通过属性区分方向,例如left-item和right-item,更语义化
子组件内部正确声明插槽并绑定作用域属性
在子组件模板中,这样写左右列表项的插槽:
<div class="list left">
<div v-for="(item, i) in leftList" :key="item.id || i">
<slot name="left-item" :item="item" :index="i" :move="() => moveToRight(item)">
{{ item.label || item.name }}
</slot>
</div>
</div>
<div class="list right">
<div v-for="(item, i) in rightList" :key="item.id || i">
<slot name="right-item" :item="item" :index="i" :move="() => moveToLeft(item)">
{{ item.label || item.name }}
</slot>
</div>
</div>
注意:默认内容(如 {{ item.label }})作为兜底展示,方便快速使用;作用域属性确保父组件能访问数据和操作。
立即学习“前端免费学习笔记(深入)”;
父组件使用时通过 v-slot 绑定并解构作用域参数
在调用穿梭框的地方,用 v-slot:left-item 和 v-slot:right-item 定制每一项:
<transfer-box :data="options">
<template #left-item="{ item, move }">
<div class="custom-item">
<span class="avatar">{{ item.avatar }}</span>
<span class="name">{{ item.name }}</span>
<button @click="move" class="btn-add">→</button>
</div>
</template>
<template #right-item="{ item, move }">
<div class="custom-item">
<img :src="item.avatarUrl" alt="" class="avatar-img"/>
<span class="title">{{ item.title }}</span>
<button @click="move" class="btn-remove">←</button>
</div>
</template>
</transfer-box>
这样左右两边可完全独立定制结构、样式和交互逻辑,比如加头像、图标、状态标签等。
进阶:支持多选 + 批量操作的插槽扩展
若需支持勾选再批量移动,可在作用域中增加 checked 状态和 toggle 方法:
- 子组件维护一个
leftChecked/rightChecked数组 - 插槽透传
checked布尔值和toggle函数 - 父组件在模板里加 checkbox,并绑定
@change="toggle" - 同时提供
moveSelectedToRight等批量方法供外部调用
这样既保持插槽灵活性,又不破坏原有单条操作逻辑。


















