请基于elementui封装一个穿梭框组件(带有父子组件)
时间: 2023-08-31 21:30:00 浏览: 134
vue2基于element-ui封装的穿梭框,可树形,可平级,可多选
好的,以下是一个基于 Element UI 的穿梭框组件的示例代码:
```
<template>
<div class="el-transfer">
<div class="el-transfer-panel">
<p>{{ leftTitle }}</p>
<el-input v-model="leftFilter" placeholder="请输入关键字搜索"></el-input>
<el-transfer-panel :filterable="true" filter-placeholder="请输入关键字搜索" :data="leftData" v-model="leftSelected" :title="leftTitle" @change="handleChange"></el-transfer-panel>
</div>
<div class="el-transfer-buttons">
<el-button :disabled="leftSelected.length === 0" type="primary" size="small" @click="handleAdd">添加</el-button>
<el-button :disabled="rightSelected.length === 0" size="small" @click="handleRemove">移除</el-button>
</div>
<div class="el-transfer-panel">
<p>{{ rightTitle }}</p>
<el-input v-model="rightFilter" placeholder="请输入关键字搜索"></el-input>
<el-transfer-panel :filterable="true" filter-placeholder="请输入关键字搜索" :data="rightData" v-model="rightSelected" :title="rightTitle" @change="handleChange"></el-transfer-panel>
</div>
</div>
</template>
<script>
export default {
name: "ElTransfer",
props: {
leftTitle: {
type: String,
default: "列表一"
},
rightTitle: {
type: String,
default: "列表二"
},
leftData: {
type: Array,
default: () => []
},
rightData: {
type: Array,
default: () => []
},
value: {
type: Array,
default: () => []
}
},
data() {
return {
leftSelected: [],
rightSelected: [],
leftFilter: "",
rightFilter: ""
};
},
watch: {
value: {
immediate: true,
handler(newVal) {
this.leftSelected = [];
this.rightSelected = [];
for (let i = 0; i < newVal.length; i++) {
if (this.leftData.findIndex(item => item === newVal[i]) !== -1) {
this.leftSelected.push(newVal[i]);
} else if (this.rightData.findIndex(item => item === newVal[i]) !== -1) {
this.rightSelected.push(newVal[i]);
}
}
}
}
},
methods: {
handleChange() {
this.$emit("input", [...this.leftSelected, ...this.rightSelected]);
},
handleAdd() {
this.$emit("input", [...this.value, ...this.leftSelected]);
this.leftSelected = [];
},
handleRemove() {
this.$emit("input", this.value.filter(item => !this.rightSelected.includes(item)));
this.rightSelected = [];
}
}
};
</script>
```
此组件包含两个穿梭框面板,分别用于显示左侧和右侧的数据。每个面板都包含一个标题、一个搜索框和一个穿梭框。通过 `props` 传递左侧和右侧的数据、标题等信息,通过 `v-model` 双向绑定父组件中的数据。用户在选中左侧或右侧的数据后,点击添加或移除按钮即可将数据添加或移除到父组件中。可以通过 `@change` 监听穿梭框的变化,实时更新父组件中的数据。
阅读全文