Tips for automatically updating the "order" attribute of an item within VueDraggable

Looking for guidance on how to update the order of items after a drag and drop functionality in Vue3 using vue draggable. The library used can be found at https://github.com/SortableJS/vue.draggable.next.

  "items": [
    {
      "name": "Test - 1",
      "order": 0
    },
    {
      "name": "Test - 2",
      "order": 1
    },
    {
      "name": "Test - 3",
      "order": 2
    }
  ]
}

If I were to move Test - 2 to the top, the updated result should look like this:

  "items": [
    {
      "name": "Test - 2",
      "order": 0
    },
    {
      "name": "Test - 1",
      "order": 1
    },
    {
      "name": "Test - 3",
      "order": 2
    }
  ]
}

Answer №1

simply iterate through the items every time the order changes
here's a complete working example:

<template>
    <draggable :list="items" 
               item-key="name"
               @change="onChange">
        <template #item="{ element }">
            <div class="list-group-item">
                {{ element.name }}
            </div>
        </template>
    </draggable>
</template>

<script>
import draggable from 'vuedraggable'

export default {
    components: {
        draggable,
    },
    data() {
        return {
            items: [
                {
                    name: 'Test - 1',
                    order: 0,
                },
                {
                    name: 'Test - 2',
                    order: 1,
                },
                {
                    name: 'Test - 3',
                    order: 2,
                },
            ],
        }
    },
    methods: {
        onChange(event) {
            this.reorder()
        },
        reorder() {
            this.items.forEach((item, index) => (item.order = index))
        },
    },
}
</script>

https://i.sstatic.net/AFW8l.gif

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a cube with unique textures on each face in three.js r81: What's the best way to achieve this?

After updating to the latest version of three.js, I encountered an issue where THREE.ImageUtils.loadTexture no longer works. As a result, I tried searching for examples of cubes with different faces, but they all utilized the outdated technique "new THREE. ...

yii2: What could be causing my JavaScript registration issue in Heroku?

Currently, I am working on a reservation application for gym training sessions as my final project for the course. However, I have encountered an issue with my script that seems to work perfectly fine when tested locally but fails when deployed on Heroku. ...

JavaScript validation for radio buttons that are grouped together

Need help with a JavaScript validation issue regarding grouped radio buttons named optionRadios1 to 5. I'm trying to validate them before submitting the form, but my code isn't working as expected and still allows the form submission. Below is t ...

Issues have been encountered with activating checkboxes on Internet Explorer while utilizing ASP.NET CheckBox controls

I'm facing an issue with an HTML form that includes two disabled checkboxes and an image with an onclick event intended to display a popup and enable the checkboxes: <input id="chk1" type="checkbox" disabled="disabled" /> <input id="chk2" ty ...

I'm having trouble locating the documents I recently saved in my mongoose model

Here is my current challenge: I am populating a collection called "fruits" with some values. Once the data has been inserted, I want to use map to console.log each fruit individually. However, during the first attempt, instead of displaying a single fruit ...

Mastering the art of sorting HTML tables with various columns using JavaScript and jQuery

When they click the button, it should alphabetize the rows in the table according to the clicked column. Is there a way to achieve this sorting functionality without using a javascript/jquery plugin or library? I prefer to develop my own code for this pa ...

Is it possible to use Three.js camera lookAt function without any rolling?

In my game, there is a square level where a ball can roll around. I am trying to adjust the camera position so that it follows the ball but always looks at 0, 0, 0. Moving the camera x and z towards the ball's position gets me close, but as seen in th ...

tips for transitioning between various json entities

Recently, I created a login page code using JavaScript that runs on a Node Express.js server. Users can input their username/email and password, and all the data gets stored in a JSON file structured like this: {"username":"admin"," ...

Using JavaScript and AJAX to manage and control a shell interface

Looking to create an HTML page that includes a YouTube video and utilizes JavaScript with the YouTube API. The objective is to embed a video and test if it has been fully downloaded using the YouTube API. I have set up an Apache server with MySQL and PHP ...

Structure of Sencha Touch application

I'm a novice with Sencha Touch and am currently developing a basic application that includes a login form and displays results in lists. My main dilemma is about the structure of the application. Would it be best to have everything contained within a ...

What could be causing the value of response.name to be undefined in this situation?

Despite extensively searching through various StackOverflow threads, none of the suggested solutions seemed to work for my specific scenario. Upon analyzing the response using console.log(response), I received an "Object Object" message. I am puzzled as to ...

Benefits of Utilizing Object.create

Unlike the referenced question, this code snippet is sourced from the book "JavaScript: The Definitive Guide". It introduces an inherit method that applies Object.create if available, but falls back to traditional JavaScript inheritance when it's not. ...

Node.JS function using try catch block

Is the following function suitable for use with Async Node.JS? I am wondering if it is written correctly, whether errors will be handled properly, or if it has been incorrectly implemented in terms of Async Node.JS. If there are issues with the implemen ...

What is the reason behind Express serving the static file through the router, while also causing the path to the scripts folder to

Directory Layout app ├── app.js ├── public │   ├── data │   │   └── data.json │   ├── index.html │   └── js │   ├── filter-list.js └── routes └── index.js Setting up ap ...

Enrollment in the course is conditional on two words being a perfect match

I have a concept in mind, but I'm struggling to piece it together. I have bits of different methods that just don't seem to align. That's why I'm reaching out for your expertise. Let's say I have 3 content containers with the clas ...

Could you kindly double-check the app id setting before executing npm run dev to avoid any issues?

Upon running npm run dev, I encountered the following message: DisabledForUser Please ensure that the app id is correctly set. In my app.blade.php file, I have imported both javascript and css. Inside the home.blade.php file, I included a div with the id ...

What causes the mounted hook in Vue to be triggered multiple times when used within a plugin or mixin?

How can I prevent repetitive behavior in my code? Is this a bug that needs fixing? Take a look at the plugin below: const globala = { install(Vue) { Vue.mixin({ mounted() { console.log('hi') } }) } } And here&apos ...

The React Context Value keeps coming back as undefined every time

As a beginner working with contexts, I am taking it slow. Recently, I came across logging Providers to test the value and encountered a constant 'undefined' result. To troubleshoot, I tried moving them side by side in the code to see if it makes ...

Utilize the Google Drive API to easily upload an Excel file

I'm encountering an issue with the Google Drive API. I've been attempting to upload an Excel file using this API, but haven't had any success. I even tried following the instructions in the Google API documentation without luck. Below is a ...

Cloud Firestore query error in Firebase Cloud Function despite data being present in Cloud Firestore

I'm facing an issue with my cloud function. The function is designed to query data from a Cloud Firestore collection, which exists. However, when I call the function from my iOS app, it always goes to the else statement and prints "NOT IN COLLECTION." ...