vue自己实现穿梭框
Vue 实现穿梭框组件
穿梭框(Transfer)是一种常见的前端组件,用于在两个列表之间移动数据项。以下是一个基于 Vue 的自定义穿梭框实现方法。
基本结构设计
穿梭框通常由两个列表(左侧和右侧)和操作按钮组成。使用 Vue 的模板可以这样设计:
<template>
<div class="transfer-container">
<div class="transfer-list">
<h3>可选列表</h3>
<ul>
<li v-for="item in leftList" :key="item.id">
<input type="checkbox" v-model="item.checked">
{{ item.label }}
</li>
</ul>
</div>
<div class="transfer-actions">
<button @click="moveToRight">→</button>
<button @click="moveToLeft">←</button>
</div>
<div class="transfer-list">
<h3>已选列表</h3>
<ul>
<li v-for="item in rightList" :key="item.id">
<input type="checkbox" v-model="item.checked">
{{ item.label }}
</li>
</ul>
</div>
</div>
</template>
数据模型
数据模型需要维护两个列表的状态:
<script>
export default {
data() {
return {
leftList: [
{ id: 1, label: '选项1', checked: false },
{ id: 2, label: '选项2', checked: false },
// 更多选项...
],
rightList: []
}
},
methods: {
moveToRight() {
this.leftList.forEach(item => {
if (item.checked) {
this.rightList.push({...item, checked: false})
}
})
this.leftList = this.leftList.filter(item => !item.checked)
},
moveToLeft() {
this.rightList.forEach(item => {
if (item.checked) {
this.leftList.push({...item, checked: false})
}
})
this.rightList = this.rightList.filter(item => !item.checked)
}
}
}
</script>
样式美化
添加基本样式使组件更美观:
<style scoped>
.transfer-container {
display: flex;
justify-content: space-between;
width: 600px;
}
.transfer-list {
width: 250px;
height: 300px;
border: 1px solid #ddd;
overflow-y: auto;
}
.transfer-actions {
display: flex;
flex-direction: column;
justify-content: center;
padding: 0 10px;
}
button {
margin: 5px 0;
padding: 5px 10px;
}
</style>
功能增强
可以添加全选/全不选功能:
methods: {
selectAll(list) {
list.forEach(item => item.checked = true)
},
unselectAll(list) {
list.forEach(item => item.checked = false)
}
}
双向绑定支持
为增强组件的复用性,可以通过 props 和 $emit 实现双向绑定:
props: {
value: {
type: Array,
default: () => []
},
dataSource: {
type: Array,
default: () => []
}
},
computed: {
leftList() {
return this.dataSource.filter(item =>
!this.value.includes(item.id)
)
},
rightList() {
return this.dataSource.filter(item =>
this.value.includes(item.id)
)
}
}
性能优化
对于大数据量,可以使用虚拟滚动:
<ul>
<li v-for="item in visibleItems" :key="item.id">
<!-- 内容 -->
</li>
</ul>
完整组件示例
将上述各部分组合起来,就可以创建一个功能完整的 Vue 穿梭框组件。可以根据实际需求添加更多功能,如搜索过滤、拖拽排序等。







