Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue实现一个列表拖拽排序 #17

Open
heyach opened this issue Sep 29, 2021 · 0 comments
Open

Vue实现一个列表拖拽排序 #17

heyach opened this issue Sep 29, 2021 · 0 comments

Comments

@heyach
Copy link
Owner

heyach commented Sep 29, 2021

前言


项目中经常会要求对一些看板,菜单的顺序做调整。

实现方案


被拖拽的元素一般是以一个列表的形式,通过拖拽事件(dragstart,dragenter,dragend)记录被拖拽的元素,经过的元素,和放置的最终位置,来维护一个列表,实时以动画更新列表。

vue实现

先维护一个List和2个变量用作记录和交换

List[
    { id1, title"item 1" },
    { id2, title"item 2" },
    { id3, title"item 3" },
    { id4, title"item 4" },
    { id5, title"item 5" },
    { id6, title"item 6" },
    { id7, title"item 7" },
],
oldItemnull,
newItemnull,

渲染列表和添加过渡效果

<transition-group name="list-item-action">
    <div
        class="drag-list"
        v-for="item in List"
        :key="item.id"
        draggable="true"
        @dragstart="dragstart(item)"
        @dragenter="dragenter(item)"
        @dragend="dragend(item)"
    >
        {{ item.title }}
    </div>
</transition-group>
.list-item-action-move {
    transition: transform 1s;
}

拖拽交换

// 记录初始信息
dragstart(item) {
    this.oldItem = item;
},
// 记录过程中信息,可以在这里实现实时交换
dragenter(item) {
    this.newItem = item;
},
// 做最终操作
dragend(item) {
    if (this.oldItem != this.newItem) {
        let oldIndex = this.List.indexOf(this.oldItem);
        let newIndex = this.List.indexOf(this.newItem);
        let newList = [...this.List]; // 中间数组,用于交换两个节点
        // 删除老的节点
        newList.splice(oldIndex, 1);
        // 在列表目标位置增加新的节点
        newList.splice(newIndex, 0, this.oldItem);
        // 更新this.List,触发transition-group的动画效果
        this.List = [...newList];
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant