使用 vue 3 从组合 API 中移动数组中的对象

Move object in array from composition API with vue 3

我想知道如何使用可拖动 (vuedraggable) 从组合 API 中移动数组中的对象。

目前我有这个:

// State
const state = reactive({
    post: null,
});

export default function postStore() {

    // Mutations
    const MOVE_COMMENT = (payload) => {
        let comment = state.post.comments[payload.oldIndex]
        
        state.post.comments.splice(payload.oldIndex, 1)
        state.post.comments.splice(payload.newIndex, 0, comment)
    };

    // Actions
    const moveComment = (payload) => {
        MOVE_COMMENT(payload)
    };

    return {
        ...toRefs(state),
        moveComment
    }
}

然后我从我的组件调用我的函数:

import draggable from 'vuedraggable';

...

<draggable :list="post.comments" @end="onEndDraggable">
    <template #item="{element}">
        <div>{{element.title}}</div>
    </template>
</draggable>

...

setup() {
    let { post, moveComment } = postStore();

    let onEndDraggable = (data) => {
        moveComment({
            newIndex: data.newIndex,
            oldIndex: data.oldIndex
        })
    }

    return { onEndDraggable }
}

当我将第一个项目拖到第二个位置时,第一个项目仍然是第一个项目。但是如果我把第一个项目拖到第三个位置,第一个项目变成第二个项目..

使用 :modelValue 而不是 :list demo

<draggable :modelValue="post.comments" item-key="title" @end="onEndDraggable">
    <template #item="{element}">
        <div>{{element.title}}</div>
    </template>
</draggable>