【问题标题】:Move object in array from composition API with vue 3使用Vue 3从组合API中移动数组中的对象
【发布时间】: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 }
}

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

【问题讨论】:

标签: vue.js vuejs3 vue-composition-api


【解决方案1】:

使用 :modelValue 代替 :list demo

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

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 2020-12-20
    • 2020-12-08
    • 2021-01-14
    • 2020-05-28
    • 2021-04-22
    • 2021-05-25
    • 1970-01-01
    相关资源
    最近更新 更多