使用Vue3+elementPlus的Tree組件實(shí)現(xiàn)一個(gè)拖拽文件夾管理

1、前言

最近在做一個(gè)文件夾管理的功能,要實(shí)現(xiàn)一個(gè)樹狀的文件夾面板。里面包含兩種元素,文件夾以及文件。交互要求如下:

  1. 創(chuàng)建、刪除,重命名文件夾和文件
  2. 可以拖拽,拖拽文件到文件夾中,或著拖拽文件夾到文件夾中
  3. 文件夾可展開,顯示里面全部文件
  4. 拖拽的時(shí)候要有輔助線顯示
拖拽文件夾.gif

2、分析

根據(jù)這個(gè)要求,我先找到了vue.draggable.next這個(gè)庫,結(jié)合elementPlus的Collapse折疊面板,以及Vue 3的遞歸組件封裝了一個(gè)組件drag-folder,結(jié)果測(cè)試發(fā)現(xiàn),這個(gè)庫太久沒維護(hù)了,很多事件不支持,導(dǎo)致功能很難實(shí)現(xiàn)。比如,拖動(dòng)的時(shí)候拿不到拖動(dòng)對(duì)象所選中的目標(biāo)、沒有輔助線、Collapse折疊面板關(guān)閉后無法拖入等問題。

就在頭疼之時(shí),我不小心看到了elementPlus的Tree組件,發(fā)現(xiàn)它也支持拖拽,而且有輔助線,有豐富的回調(diào)事件,于是,我準(zhǔn)備魔改一下。

3、 實(shí)現(xiàn)

Tree組件只需要準(zhǔn)備一個(gè)樹狀數(shù)據(jù),然后根據(jù)數(shù)據(jù)渲染出Tree組件即可,可以自定義子節(jié)點(diǎn)的鍵名,也可以使用插槽自定義內(nèi)容,于是一番操作后,我完成了第二版的drag-folder組件:

<template>
    <div class="drag_folder_box">
        <el-tree
            draggable
            node-key="uid"
            :default-expanded-keys="defaultExpanded"
            :data="interiorList"
            :allow-drop="handleDragBehavior"
            :allow-drag="handleAllowDrag"
            @node-drag-start="handleDragStart"
            @node-drag-enter="handleDragEnter"
            @node-drag-leave="handleDragLeave"
            @node-drag-over="handleDragOver"
            @node-drag-end="handleDragEnd"
            @node-drop="handleDrop"
            @node-click="handleSwitchBillboard"
        >
            <template #default="{ data }">
                <div class="tree_item">
                    <div class="item_title">{{ data.label }}</div>
                    <div class="item_operate">
                        <div class="operate_item" title="編輯" @click.stop="editBillboard(data)">
                            <el-icon :size="16">
                                <ele-Edit />
                            </el-icon>
                        </div>
                        <div class="operate_item" title="刪除" @click.stop="deleteBillboard(data)">
                            <el-icon :size="16">
                                <ele-Delete />
                            </el-icon>
                        </div>
                    </div>
                </div>
            </template>
        </el-tree>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import type { DragEvents } from 'element-plus/es/components/tree/src/model/useDragNode'
import type { AllowDropType, NodeDropType } from 'element-plus/es/components/tree/src/tree.type'
import type { IGetBillboardListTreeItem } from '@/types/data-billboard'

// #region 組件邏輯
interface IProps {
    list?: Array<IGetBillboardListTreeItem>
}

const props = withDefaults(defineProps<IProps>(), {
    list: () => []
})

const emit = defineEmits(['edit', 'delete', 'switch', 'change'])

const interiorList = ref<Array<IGetBillboardListTreeItem>>([])
// #endregion

// #region 拖拽邏輯
watch(
    () => props.list,
    (newValue) => {
        interiorList.value = newValue
    },
    {
        deep: true,
        immediate: true
    }
)
// 節(jié)點(diǎn)開始拖拽時(shí)
const handleDragStart = (node: Node, ev: DragEvents) => {}

// 拖拽進(jìn)入其他節(jié)點(diǎn)時(shí)
const handleDragEnter = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {}

// 拖拽離開某個(gè)節(jié)點(diǎn)時(shí)
const handleDragLeave = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {}

// 在拖拽節(jié)點(diǎn)時(shí)
const handleDragOver = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {}

// 拖拽結(jié)束時(shí)
const handleDragEnd = (draggingNode: Node, dropNode: Node, dropType: NodeDropType, ev: DragEvents) => {}

// 拖拽成功時(shí)
const handleDrop = (draggingNode: Node, dropNode: Node, dropType: NodeDropType, ev: DragEvents) => {
    emit('change', interiorList.value)
}
// 是否允許拖拽
const handleAllowDrag = (draggingNode: Node) => {
    return true
}
// 拖拽行為判斷
const handleDragBehavior = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
    // 如果選中的節(jié)點(diǎn)不是看板 則不允許拖動(dòng)到內(nèi)部,只能是 'prev' 或 'next'
    if (dropNode.data.type === 'billboard') {
        return type !== 'inner'
    }
    return true
}

// 編輯看板/文件夾
const editBillboard = (data: IGetBillboardListTreeItem) => {
    emit('edit', data)
}

// 刪除看板/文件夾
const deleteBillboard = (data: IGetBillboardListTreeItem) => {
    emit('delete', data)
}

// 選擇看板
const handleSwitchBillboard = (data: IGetBillboardListTreeItem) => {
    if (data.type === 'dir') return
    if (data.id === props.billboardId) return
    emit('switch', data)
}
// #endregion

// #region 生命周期
onMounted(() => {
    interiorList.value = props?.list || []
})
// #endregion
</script>

這個(gè)組件,使用起來很簡(jiǎn)單,只需要引入組件,然后綁定list就行了,下面我講一下這里面的一些坑。

4、踩坑

這里面有幾個(gè)坑,但是基本都解決了。

4.1、拖拽輔助線的坑

Tree組件沒有itemSize屬性,它的輔助線,默認(rèn)是26px,而我的每一項(xiàng),是36px的高度,所以就會(huì)導(dǎo)致輔助線不能對(duì)準(zhǔn)。


輔助線歪了.png

最開始我想著修改樣式,給height和line-height,發(fā)現(xiàn)不起作用。于是我去翻源碼,發(fā)現(xiàn)源碼:node_modules\element-plus\lib\components\tree\src\model\useDragNode.js里,treeNodeDragOver方法是給輔助線設(shè)置top的,這個(gè)top是根據(jù)前面的iconPosition的高度來的,所以我設(shè)置了icon的height和line-height,一頓操縱如下:

.el-tree-node__expand-icon {
    line-height: 36px !important;
    height: 36px !important;
    padding: 0px 2px !important;
}

改完發(fā)現(xiàn),面板折疊起來是正常的,但是打開后就還是不正常,審查元素發(fā)現(xiàn),這個(gè)icon會(huì)旋轉(zhuǎn),打開面板后會(huì)添加一個(gè)expanded的類名,該類名添加了transform: rotate(90deg)的屬性,導(dǎo)致高度不對(duì)了,于是我又一頓操作:

.el-tree-node__expand-icon {
    line-height: 36px !important;
    height: 36px !important;
    padding: 0px 2px !important;
}
.el-tree-node__expand-icon.expanded {
    transform: rotate(0deg);
    & svg {
        transform: rotate(90deg);
    }
}

4.2、數(shù)據(jù)的坑

這個(gè)是我們后端設(shè)計(jì)的鍋。文件夾和文件的ID,會(huì)出現(xiàn)一樣的,沒有唯一ID,沒辦法,誰讓我們前端就是這么善解人意,寫個(gè)遞歸函數(shù),拼接一個(gè)唯一ID出來咯。

const formatBillboardList = (list: Array<IBillboardTreeItem>, pid: number): Array<IBillboardTreeItem> => {
    return list.map((item, index) => {
        // 唯一ID
        const uid = `${item.type}_${item.id}`
        // 父ID
        const parentId = pid === 0 ? item.id : pid
        // 子層
        const children = Array.isArray(item.children) ? formatBillboardList(item.children, item.id) : []
        return {
            ...item,
            uid,
            order: index,
            parentId,
            children
        }
    })
}

const list = formatBillboardList(res.data, 0)

4.3、限制拖拽

文件夾和文件,都是可以拖拽的,但是文件可以拖拽到文件夾上,文件夾不能拖拽到文件里。這里我們用到了Tree組件的allow-drop處理函數(shù),它又三個(gè)參數(shù),分別是拖拽對(duì)象,目標(biāo)對(duì)象,拖拽類型。

const handleDragBehavior = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
    // 如果選中的節(jié)點(diǎn)不是看板 則不允許拖動(dòng)到內(nèi)部,只能是 'prev' 或 'next'
    if (dropNode.data.type === 'billboard') {
        return type !== 'inner'
    }
    return true
}

4.4、樣式調(diào)整

  • 文件夾和文件的樣式不一樣,要區(qū)分,這里我們用Tree組件的props屬性,定制class實(shí)現(xiàn)
const treeOption = {
    class: (data: IGetBillboardListTreeItem, node: Node) => {
        if (data.id === props.billboardId && data.type === 'billboard') {
            return 'on_tree_item'
        } else if (data.type === 'dir') {
            return 'folder'
        } else {
            return 'billboard'
        }
    }
}
  • 每一層,要有不同的縮進(jìn),比如第一層縮進(jìn)10,第二層20,以此類推,這里我們用Tree組件的indent屬性實(shí)現(xiàn),直接綁定即可。
<el-tree :indent="10"></el-tree>
  • 修改hover和focus時(shí)候的背景色
.drag_folder_box {
  &:deep(.el-tree-node__content) {
        width: 100%;
        height: auto;
        border-bottom: 1px solid #c1c1c1;
        &:hover {
            background-color: #e4f2ff !important;
        }
        &:focus {
            background-color: #e4f2ff !important;
        }
    }
}

如上,基本的樣式和功能就全部完成了。


本次分享就到這兒啦,我是@鵬多多,如果您看了覺得有幫助,歡迎評(píng)論,關(guān)注,點(diǎn)贊,轉(zhuǎn)發(fā),我們下次見~

PS:在本頁按F12,在console中輸入document.querySelectorAll('._2VdqdF')[0].click(),有驚喜哦

往期文章

個(gè)人主頁

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容