【发布时间】:2021-08-20 18:20:45
【问题描述】:
我想知道如何使用可拖动 (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 }
}
当我将第一个项目拖到第二个位置时,第一个项目仍然是第一个项目。但是如果我将第一个项目拖到第三个位置,第一个项目就会变成第二个项目..
【问题讨论】:
-
您的代码似乎是work correctly:它将旧项目向下移动,将中间项目移向
oldIndex。为什么你说它不起作用? -
感谢@tony19 的评论!我更新了我的代码并根据您的代码创建了一个演示 stackblitz.com/edit/vue-shifting-array-elements-wpdmq9
标签: vue.js vuejs3 vue-composition-api