這篇文章主要介紹了vue element el-transfer增加拖拽功能,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
芯資管項目要求el-transfer增加拖拽排序,左右上下互相拖拽功能;
原來的組件不支持拖拽,這里要用個第三方脫宅組件sortablejs
首先安裝
sudo npm i sortablejs --save-dev
html代碼
<template> <el-transfer ref="transfer" id="transfer" v-model="value" :data="data"> <span slot-scope="{ option }" :draggable="!option.disabled" @dragstart="drag($event,option)">{{ option.key }} - {{ option.label }}</span> </el-transfer> </template>
create
<script> import Sortable from 'sortablejs' export default { data() { const generateData = _ => { const data = []; for (let i = 1; i <= 15; i++) { data.push({ key: i, label: `備選項 ${i}`, disabled: i % 4 === 0 }); } return data; }; return { data: generateData(), value: [1, 4], draggingKey : null } }, mounted() { const transfer = this.$refs.transfer.$el const leftPanel = transfer.getElementsByClassName("el-transfer-panel")[0].getElementsByClassName("el-transfer-panel__body")[0]; const rightPanel = transfer.getElementsByClassName("el-transfer-panel")[1].getElementsByClassName("el-transfer-panel__body")[0]; const rightEl = rightPanel.getElementsByClassName("el-transfer-panel__list")[0] Sortable.create(rightEl,{ onEnd: (evt) => { const {oldIndex,newIndex} = evt; const temp = this.value[oldIndex] if (!temp || temp === 'undefined') { return }// 解決右邊最后一項從右邊拖左邊,有undefined的問題 this.$set(this.value,oldIndex,this.value[newIndex]) this.$set(this.value,newIndex,temp) } }) const leftEl = leftPanel.getElementsByClassName("el-transfer-panel__list")[0] Sortable.create(leftEl,{ onEnd: (evt) => { const {oldIndex,newIndex} = evt; const temp = this.data[oldIndex] if (!temp || temp === 'undefined') { return } // 解決右邊最后一項從右邊拖左邊,有undefined的問題 this.$set(this.data,oldIndex,this.data[newIndex]) this.$set(this.data,newIndex,temp) } }) leftPanel.ondragover = (ev) => { ev.preventDefault() } leftPanel.ondrop = (ev) => { ev.preventDefault(); const index = this.value.indexOf(this.draggingKey) if(index !== -1){ this.value.splice(index,1) } } rightPanel.ondragover = (ev) => { ev.preventDefault() } rightPanel.ondrop = (ev) => { ev.preventDefault(); if(this.value.indexOf(this.draggingKey) === -1){ this.value.push(this.draggingKey) } } }, methods: { drag(ev,option) { this.draggingKey = option.key } } } </script>
到此這篇關于vue element el-transfer增加拖拽功能的文章就介紹到這了。