用vue 写一个穿梭框
时间: 2023-07-01 08:07:21 浏览: 79
el-tree实现el-transfer(穿梭框)的效果代码(全)
5星 · 资源好评率100%
好的,以下是一个简单的Vue穿梭框组件:
```html
<template>
<div class="transfer-box">
<h3>可选项</h3>
<ul class="transfer-list">
<li v-for="(option, index) in options" :key="index" v-show="!option.checked">
<label>
<input type="checkbox" v-model="option.checked" @change="onChange(index, option)">
{{ option.label }}
</label>
</li>
</ul>
<button @click="addToSelected">添加</button>
<button @click="removeFromSelected">移除</button>
<h3>已选项</h3>
<ul class="transfer-list">
<li v-for="(option, index) in selectedOptions" :key="index" v-show="option.checked">
<label>
<input type="checkbox" v-model="option.checked" @change="onChange(index, option)">
{{ option.label }}
</label>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "TransferBox",
props: {
options: {
type: Array,
required: true,
},
},
data() {
return {
selectedOptions: [],
};
},
methods: {
addToSelected() {
this.options.forEach((option) => {
if (option.checked) {
option.checked = false;
this.selectedOptions.push(option);
}
});
},
removeFromSelected() {
this.selectedOptions.forEach((option) => {
if (option.checked) {
option.checked = false;
this.options.push(option);
}
});
this.selectedOptions = this.selectedOptions.filter(
(option) => !option.checked
);
},
onChange(index, option) {
if (this.selectedOptions.indexOf(option) !== -1) {
this.$set(this.selectedOptions, index, option);
} else {
this.$set(this.options, index, option);
}
},
},
};
</script>
<style>
.transfer-box {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin-top: 20px;
}
.transfer-list {
list-style-type: none;
padding: 0;
width: 150px;
height: 150px;
border: 1px solid #ccc;
overflow-y: scroll;
margin-right: 10px;
}
.transfer-list li {
margin: 5px 0;
}
button {
margin-top: 50px;
font-size: 16px;
padding: 5px 15px;
border-radius: 3px;
border: none;
background-color: #007aff;
color: #fff;
}
button:hover {
cursor: pointer;
}
</style>
```
这里的核心逻辑是将选中的选项从可选项列表中移动到已选项列表中,以及将已选项列表中的选项移回到可选项列表中。通过checkbox的v-model绑定,可以方便地实现选中状态的同步。同时,onChange方法可以用来处理选中状态的改变,并将相应的选项从一个列表移动到另一个列表中。
阅读全文